# -*- coding: utf-8 -*-
"""Untitled6.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1jBo6gJI5KOYmsEssDN9i0YecdyrUrIsr
"""

from google.colab import output
output.enable_custom_widget_manager()



import os
os.environ['HF_TOKEN_DIARIZATION'] = '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'

!pip install pyannote.audio



import torch
import librosa
from pyannote.audio import Pipeline

# Set the device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Load the pre-trained diarization pipeline with the token
diarization_pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization", use_auth_token=os.getenv('HF_TOKEN_DIARIZATION'))

# Path to your audio file
audio_file = "/content/sample_data/sample.wav"  # Replace with the actual path to your audio file

# Load the audio file using librosa
y, sr = librosa.load(audio_file, sr=None)

# Apply diarization
diarization = diarization_pipeline(audio_file)

# Print the diarization results
for turn, _, speaker in diarization.itertracks(yield_label=True):
    print(f"Speaker {speaker} from {turn.start:.1f}s to {turn.end:.1f}s")

import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np

# Load the audio file
audio_file = "/content/sample_data/sample.wav"  # Replace with your file path
y, sr = librosa.load(audio_file, sr=None)

# Compute the spectrogram (Short-Time Fourier Transform - STFT)
S = librosa.stft(y)
S_db = librosa.amplitude_to_db(np.abs(S), ref=np.max)

# Plot the spectrogram
plt.figure(figsize=(10, 6))
librosa.display.specshow(S_db, sr=sr, x_axis='time', y_axis='log')
plt.colorbar(format="%+2.0f dB")
plt.title('Spectrogram')
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')
plt.show()

import torch
import librosa
import numpy as np
import matplotlib.pyplot as plt
from pyannote.audio import Pipeline
import os

# Set up device (GPU if available)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Load pre-trained speaker diarization pipeline
diarization_pipeline = Pipeline.from_pretrained(
    "pyannote/speaker-diarization",
    use_auth_token=os.getenv('HF_TOKEN_DIARIZATION')
)

# Load the audio file
audio_file = "/content/sample_data/sample.wav"  # Replace with your file path
y, sr = librosa.load(audio_file, sr=None)

# Run speaker diarization
diarization = diarization_pipeline(audio_file)

# Initialize storage for F0 data
f0_per_speaker = {}

# Extract F0 for each speaker
for turn, _, speaker in diarization.itertracks(yield_label=True):
    # Get the time window for the speaker's segment
    start_sample = int(turn.start * sr)
    end_sample = int(turn.end * sr)
    speaker_segment = y[start_sample:end_sample]

    # Extract F0 using librosa's piptrack
    f0, _ = librosa.piptrack(y=speaker_segment, sr=sr)

    # Average F0 over time (ignoring zeros)
    mean_f0 = np.mean(f0[f0 > 0])

    # Store the F0 data
    if speaker not in f0_per_speaker:
        f0_per_speaker[speaker] = []
    f0_per_speaker[speaker].append(mean_f0)

# Calculate overall mean F0 for each speaker
for speaker, f0_values in f0_per_speaker.items():
    overall_mean_f0 = np.mean(f0_values)
    print(f"Speaker {speaker}: Mean F0 = {overall_mean_f0:.2f} Hz")

!pip install librosa
!pip install numpy

import librosa
import time
import numpy as np

# Function to calculate proportional distance (number of cycles)
def calculate_proportional_distance(F0, delta_t):
    proportional_distance = F0 * delta_t
    return proportional_distance

# Load the audio file
audio_file = 'path_to_your_audio_file.wav'  # Provide your audio file path here
y, sr = librosa.load(audio_file, sr=None)  # Load the audio file with original sampling rate

# Extract the fundamental frequency (F₀) from the audio
F0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))

# Duration of the audio in seconds
audio_duration = librosa.get_duration(y=y, sr=sr)

# Start calculating proportional distance every second
for t in range(1, int(audio_duration) + 1):  # loop for each second
    # Calculate the mean fundamental frequency (F₀) for the current second (or use average F₀)
    mean_F0 = np.mean(F0[(t-1) * sr : t * sr])  # average F₀ for that second
    proportional_distance = calculate_proportional_distance(mean_F0, 1)  # calculate proportional distance for each second (Δt = 1 second)
    print(f"At {t} second(s), the proportional distance is: {proportional_distance} cycles")
    time.sleep(1)  # wait for 1 second before next calculation

import os
os.listdir()





audio_file = 'sample.wav'

import librosa

# Set the correct audio file name
audio_file = 'sample.wav'  # Update with your correct file name

# Try loading the audio file and check if it works
try:
    y, sr = librosa.load(audio_file, sr=None)  # Load the audio file with original sampling rate
    print(f"Audio file loaded successfully. Duration: {librosa.get_duration(y=y, sr=sr)} seconds.")
except Exception as e:
    print(f"Error loading audio file: {e}")

import gc
gc.collect()

!pip install librosa numpy

import librosa
import numpy as np
import matplotlib.pyplot as plt

# Load the audio file
audio_file = 'sample.wav'  # Make sure your file is correctly named and uploaded
y, sr = librosa.load(audio_file, sr=None)

# Calculate time duration of the audio
duration = librosa.get_duration(y=y, sr=sr)
print(f"Audio duration: {duration:.2f} seconds")

# Define a function to calculate F0 (fundamental frequency)
def calculate_f0(y, sr, hop_length=512):
    f0_values = librosa.yin(y, fmin=50, fmax=500, sr=sr, hop_length=hop_length)
    return f0_values

# Calculate F0
f0_values = calculate_f0(y, sr)

# Calculate time intervals (Δt = 1 second steps)
time_intervals = np.arange(0, duration, 1)

# Calculate proportional distance: F0 × Δt per second
proportional_distances = []

# Group F0 values into 1-second intervals
for t in time_intervals:
    start_sample = int(t * sr)
    end_sample = min(int((t + 1) * sr), len(y))
    f0_segment = f0_values[start_sample // 512 : end_sample // 512]
    avg_f0 = np.nanmean(f0_segment)  # Ignore NaN values
    proportional_distance = avg_f0 * 1  # Δt is 1 second
    proportional_distances.append(proportional_distance)

# Display the results
for t, dist in zip(time_intervals, proportional_distances):
    print(f"Time {int(t)}s: Proportional Distance = {dist:.2f}")

# Optional: Plot the proportional distance over time
plt.figure(figsize=(10, 5))
plt.plot(time_intervals, proportional_distances, marker='o')
plt.title('Proportional Distance per Second')
plt.xlabel('Time (s)')
plt.ylabel('Proportional Distance')
plt.grid(True)
plt.show()

# Print the duration of the audio in seconds
duration = librosa.get_duration(y=y, sr=sr)
print(f"Audio duration: {duration} seconds")

# Print the duration of the audio in seconds
duration = librosa.get_duration(y=y, sr=sr)
print(f"Audio duration: {duration} seconds")

import librosa
import numpy as np
import matplotlib.pyplot as plt

# Load the audio file
audio_file = 'path_to_your_audio_file.wav'  # Replace with your actual file path
y, sr = librosa.load(audio_file, sr=None)  # Load audio with original sampling rate

# Calculate the fundamental frequency (F0) of the audio
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Define the speed of sound in air (in meters per second)
speed_of_sound = 343  # m/s

# Initialize list for displacement (proportional to the wavelength)
displacement = []

# Loop over the fundamental frequencies and calculate the corresponding displacement (wavelength)
for i in range(len(f0)):
    if np.isnan(f0[i]):
        displacement.append(0)  # If F0 is NaN, no displacement
    else:
        wavelength = speed_of_sound / f0[i]  # Wavelength calculation (m)
        displacement.append(wavelength)

# Calculate the time intervals (seconds) for each frame
times = librosa.times_like(f0)

# Plot the displacement over time
plt.figure(figsize=(12, 6))
plt.plot(times, displacement, label="Proportional Displacement")
plt.xlabel('Time (seconds)')
plt.ylabel('Proportional Displacement (meters)')
plt.title('Proportional Displacement over Time')
plt.legend()
plt.grid(True)
plt.show()

# Optional: print out some displacement values
print(f"First few displacement values: {displacement[:10]}")

!ls

audio_file = 'sample.wav'  # Use the correct file name here
y, sr = librosa.load(audio_file, sr=None)  # Load the audio with its original sampling rate

import librosa
import numpy as np
import matplotlib.pyplot as plt

# Load the audio file
audio_file = 'path_to_your_audio_file.wav'  # Replace with your actual file path
y, sr = librosa.load(audio_file, sr=None)  # Load audio with original sampling rate

# Calculate the fundamental frequency (F0) of the audio
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Define the speed of sound in air (in meters per second)
speed_of_sound = 343  # m/s

# Initialize list for displacement (proportional to the wavelength)
displacement = []

# Loop over the fundamental frequencies and calculate the corresponding displacement (wavelength)
for i in range(len(f0)):
    if np.isnan(f0[i]):
        displacement.append(0)  # If F0 is NaN, no displacement
    else:
        wavelength = speed_of_sound / f0[i]  # Wavelength calculation (m)
        displacement.append(wavelength)

# Calculate the time intervals (seconds) for each frame
times = librosa.times_like(f0)

# Plot the displacement over time
plt.figure(figsize=(12, 6))
plt.plot(times, displacement, label="Proportional Displacement")
plt.xlabel('Time (seconds)')
plt.ylabel('Proportional Displacement (meters)')
plt.title('Proportional Displacement over Time')
plt.legend()
plt.grid(True)
plt.show()

# Optional: print out some displacement values
print(f"First few displacement values: {displacement[:10]}")

audio_file = '/content/sample.wav'  # Or '/content/sample (1).wav', based on the exact file name

# Define the file path correctly
audio_file = '/content/sample.wav'  # Update this with the exact file name, like 'sample (1).wav'

# Load the audio file
y, sr = librosa.load(audio_file, sr=None)  # Load the audio with original sampling rate
print(f"Audio file loaded successfully. Duration: {librosa.get_duration(y=y, sr=sr)} seconds.")

# Define the file path correctly
audio_file = '/content/sample.wav'  # Update this with the exact file name, like 'sample (1).wav'

# Load the audio file
y, sr = librosa.load(audio_file, sr=None)  # Load the audio with original sampling rate
print(f"Audio file loaded successfully. Duration: {librosa.get_duration(y=y, sr=sr)} seconds.")

import librosa
import numpy as np
import matplotlib.pyplot as plt

# Load the audio file
audio_file = 'path_to_your_audio_file.wav'  # Replace with your actual file path
y, sr = librosa.load(audio_file, sr=None)  # Load audio with original sampling rate

# Calculate the fundamental frequency (F0) of the audio
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Define the speed of sound in air (in meters per second)
speed_of_sound = 343  # m/s

# Initialize list for displacement (proportional to the wavelength)
displacement = []

# Loop over the fundamental frequencies and calculate the corresponding displacement (wavelength)
for i in range(len(f0)):
    if np.isnan(f0[i]):
        displacement.append(0)  # If F0 is NaN, no displacement
    else:
        wavelength = speed_of_sound / f0[i]  # Wavelength calculation (m)
        displacement.append(wavelength)

# Calculate the time intervals (seconds) for each frame
times = librosa.times_like(f0)

# Plot the displacement over time
plt.figure(figsize=(12, 6))
plt.plot(times, displacement, label="Proportional Displacement")
plt.xlabel('Time (seconds)')
plt.ylabel('Proportional Displacement (meters)')
plt.title('Proportional Displacement over Time')
plt.legend()
plt.grid(True)
plt.show()

# Optional: print out some displacement values
print(f"First few displacement values: {displacement[:10]}")

from google.colab import files
uploaded = files.upload()

import librosa

# Load the audio file
y, sr = librosa.load(audio_file, sr=None)

# Calculate duration (in seconds)
duration = librosa.get_duration(y=y, sr=sr)
print(f"Duration: {duration} seconds")

import os
print("Current directory:", os.getcwd())
print("Files in the directory:", os.listdir())

audio_file = 'sample.wav'

audio_file = 'sample.wav'  # Replace with the actual filename

import os
os.chdir('sample.wav')  # Set the working directory
print(os.getcwd())  # Confirm the current working directory

import os

# Set the path to the directory where the file is located, adjust if needed
directory = '/content/'  # Example path, if your file is in the current working directory

# Change to that directory if required
os.chdir(directory)

# Confirm the current working directory
print(f"Current working directory: {os.getcwd()}")

# Load the audio file directly without needing to change the directory again
audio_file = 'sample.wav'

# Confirm file exists in the current directory
if os.path.exists(audio_file):
    print(f"File '{audio_file}' found!")
else:
    print(f"File '{audio_file}' not found!")

import librosa
import numpy as np

# Load the audio file
audio_file = 'sample.wav'  # Update the path to your audio file
y, sr = librosa.load(audio_file, sr=None)  # Load the audio with the original sampling rate

# Calculate fundamental frequency (F₀) using librosa's pyin method
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Create an array for time
time = np.linspace(0, len(y) / sr, num=len(y))

# Calculate the proportional displacement using the formula
# Displacement (d) = wavelength * number of cycles (proportional to F₀)
# Wavelength = speed of sound / F₀ (assuming the vocal cords' movement speed matches the speed of sound)
speed_of_sound = 343  # in meters per second (at room temperature)

# Proportional displacement calculation
displacement = (speed_of_sound / f0) * (f0)  # Proportional displacement in terms of cycles

# Now, display the displacement for the first few seconds to check the output
print("Displacement calculated for the first few samples:")
print(displacement[:10])  # Display the first 10 displacement values

del y  # If 'y' is no longer needed

import librosa

audio_file = 'sample.wav'  # Your file name
y, sr = librosa.load(audio_file, sr=None)  # Reload audio file

locals()  # This will show all currently defined variables in the session

del y  # Delete the audio signal variable 'y'
import gc
gc.collect()  # Perform garbage collection to free up memory

import librosa

audio_file = 'sample.wav'  # Your file name
y, sr = librosa.load(audio_file, sr=None)  # Reload audio file

import librosa
import numpy as np

# Load the audio file
audio_file = 'sample.wav'  # Replace with the correct file path
y, sr = librosa.load(audio_file, sr=None)  # Load audio with original sampling rate

# Define a function to calculate phoneme displacement over time
def calculate_displacement(y, sr, frame_length=2048, hop_length=512):
    # Extract features that can represent phoneme occurrences
    onset_env = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length)

    # Detect onset peaks
    onset_frames = librosa.onset.onset_detect(onset_envelope=onset_env, hop_length=hop_length)

    # Get time stamps for the onsets
    onset_times = librosa.frames_to_time(onset_frames, sr=sr, hop_length=hop_length)

    # Calculate displacement (difference between onsets over time)
    initial_time = onset_times[0] if len(onset_times) > 0 else 0
    final_time = onset_times[-1] if len(onset_times) > 0 else 0

    displacement = final_time - initial_time  # Displacement is the time difference between first and last onset

    return displacement, onset_times

# Calculate displacement
displacement, onset_times = calculate_displacement(y, sr)

print(f"Displacement: {displacement} seconds")
print(f"Onset times: {onset_times}")

import os
print("Current working directory:", os.getcwd())
print("Files in the directory:", os.listdir())

import os
print("Current working directory:", os.getcwd())  # Check the current working directory
print("Files in the directory:", os.listdir())  # List files in the directory

from google.colab import files
uploaded = files.upload()  # This will allow you to upload your file

import librosa
import numpy as np

audio_file = 'sample.wav'  # Your uploaded file name
y, sr = librosa.load(audio_file, sr=None)  # Reload audio file

# Set the analysis range (e.g., 0 to 678 seconds)
start_time = 0  # in seconds
end_time = 678  # in seconds

# Get the start and end sample indices
start_sample = int(start_time * sr)
end_sample = int(end_time * sr)

# Extract the relevant portion of the signal
y_segment = y[start_sample:end_sample]

# Count the number of phonemes in the segment (using a basic threshold method)
threshold = 0.1  # Adjust threshold for phoneme detection
phonemes = np.where(np.abs(y_segment) > threshold)[0]

# Calculate displacement as the change in phoneme variety
initial_phonemes = phonemes[:len(phonemes)//2]  # First half
final_phonemes = phonemes[len(phonemes)//2:]  # Second half

displacement = len(final_phonemes) - len(initial_phonemes)
print(f"Displacement: {displacement}")

import librosa
import numpy as np
import scipy.signal as signal

# Load the audio file
audio_path = 'sample.wav'  # Update with your audio file path
y, sr = librosa.load(audio_path, sr=None)  # Load audio with the original sampling rate

# Compute the envelope using the Hilbert transform
analytic_signal = librosa.core.hilbert(y)
amplitude_envelope = np.abs(analytic_signal)

# Normalize the envelope (optional)
amplitude_envelope = amplitude_envelope / np.max(amplitude_envelope)

# Detect peaks in the envelope to find crest-to-crest cycles
peaks, _ = signal.find_peaks(amplitude_envelope, height=0.1)  # Adjust height to filter noise

# If we have at least two peaks, calculate the displacement
if len(peaks) > 1:
    # Calculate the crest-to-crest distances (wavelengths) in seconds
    crest_to_crest_distances = np.diff(peaks) / sr  # Convert from samples to seconds

    # Calculate total displacement (sum of all crest-to-crest distances)
    displacement = np.sum(crest_to_crest_distances)
    print(f"Total Displacement (in seconds): {displacement}")

else:
    print("Not enough peaks detected to calculate displacement.")

import librosa
import numpy as np
import scipy.signal as signal
from scipy.signal import hilbert  # Use SciPy's hilbert

# Load the audio file
audio_path = 'sample.wav'  # Update with your audio file path
y, sr = librosa.load(audio_path, sr=None)  # Load audio with the original sampling rate

# Compute the envelope using the Hilbert transform (using SciPy)
analytic_signal = hilbert(y)
amplitude_envelope = np.abs(analytic_signal)

# Normalize the envelope (optional)
amplitude_envelope = amplitude_envelope / np.max(amplitude_envelope)

# Detect peaks in the envelope to find crest-to-crest cycles
peaks, _ = signal.find_peaks(amplitude_envelope, height=0.1)  # Adjust height to filter noise

# If we have at least two peaks, calculate the displacement
if len(peaks) > 1:
    # Calculate the crest-to-crest distances (wavelengths) in seconds
    crest_to_crest_distances = np.diff(peaks) / sr  # Convert from samples to seconds

    # Calculate total displacement (sum of all crest-to-crest distances)
    displacement = np.sum(crest_to_crest_distances)
    print(f"Total Displacement (in seconds): {displacement}")

else:
    print("Not enough peaks detected to calculate displacement.")

import librosa
import numpy as np
import scipy.signal as signal

# Load the audio file
audio_path = 'your_audio_file.wav'  # Replace with your actual file path
y, sr = librosa.load(audio_path, sr=None)  # Load audio signal with original sampling rate

# Define the total duration (in seconds) of the audio
duration_seconds = len(y) / sr

# Initialize variables for cumulative displacement and per-second displacement
cumulative_displacement = 0
displacement_per_second = []

# Loop over each second of the audio
for t in range(int(duration_seconds)):
    # Get the start and end sample index for the current second
    start_sample = t * sr
    end_sample = (t + 1) * sr

    # Extract the segment for the current second
    y_segment = y[start_sample:end_sample]

    # Compute the envelope using the Hilbert transform for the current segment
    analytic_signal = librosa.core.hilbert(y_segment)
    amplitude_envelope = np.abs(analytic_signal)

    # Normalize the envelope
    amplitude_envelope = amplitude_envelope / np.max(amplitude_envelope)

    # Detect peaks in the envelope (crest-to-crest cycles)
    peaks, _ = signal.find_peaks(amplitude_envelope, height=0.1)  # Adjust height to filter noise

    # Calculate the number of crest-to-crest cycles (displacement) for the current second
    if len(peaks) > 1:
        # Calculate the crest-to-crest cycle distance in samples and then convert to seconds
        cycle_crest_to_crest_distance = np.diff(peaks)[0]  # Distance between two peaks
        cycle_duration = cycle_crest_to_crest_distance / sr  # Convert to seconds

        # Displacement for the current second (number of cycles)
        displacement = len(peaks) - 1

        # Add displacement to cumulative displacement
        cumulative_displacement += displacement
        displacement_per_second.append(cumulative_displacement)  # Store cumulative displacement
    else:
        displacement_per_second.append(cumulative_displacement)  # No displacement if not enough peaks detected

# Print cumulative displacement for each second
for second, cumulative_disp in enumerate(displacement_per_second):
    print(f"Second {second+1}: Cumulative Displacement = {cumulative_disp} cycles")

import librosa
import numpy as np
import scipy.signal as signal

# Load the audio file
audio_path = 'sample.wav'  # Use the correct file name here
y, sr = librosa.load(audio_path, sr=None)

# Compute the envelope using the Hilbert transform
analytic_signal = librosa.core.hilbert(y)
amplitude_envelope = np.abs(analytic_signal)

# Normalize the envelope (optional)
amplitude_envelope = amplitude_envelope / np.max(amplitude_envelope)

# Detect peaks in the envelope to find crest-to-crest cycles
peaks, _ = signal.find_peaks(amplitude_envelope, height=0.1)  # Adjust height to filter noise

# If we have at least two peaks, calculate the distance between them (period)
if len(peaks) > 1:
    cycle_crest_to_crest_distance = np.diff(peaks)[0]  # The distance between two peaks (in samples)
    print(f"Crest-to-Crest Cycle Distance (in samples): {cycle_crest_to_crest_distance}")

    # Convert to time duration (in seconds) for one cycle
    cycle_duration = cycle_crest_to_crest_distance / sr
    print(f"Duration of One Cycle (in seconds): {cycle_duration}")

    # If needed, convert this to physical displacement using a calibration factor
    # For now, this is just in terms of signal amplitude.
else:
    print("Not enough peaks detected for one cycle.")

import librosa
import numpy as np
import scipy.signal as signal

# Load the audio file
audio_path = 'sample.wav'  # Make sure this is the correct file name
y, sr = librosa.load(audio_path, sr=None)

# Compute the envelope using the Hilbert transform from scipy.signal
analytic_signal = signal.hilbert(y)
amplitude_envelope = np.abs(analytic_signal)

# Normalize the envelope (optional)
amplitude_envelope = amplitude_envelope / np.max(amplitude_envelope)

# Detect peaks in the envelope to find crest-to-crest cycles
peaks, _ = signal.find_peaks(amplitude_envelope, height=0.1)  # Adjust height to filter noise

# If we have at least two peaks, calculate the distance between them (period)
if len(peaks) > 1:
    cycle_crest_to_crest_distance = np.diff(peaks)[0]  # The distance between two peaks (in samples)
    print(f"Crest-to-Crest Cycle Distance (in samples): {cycle_crest_to_crest_distance}")

    # Convert to time duration (in seconds) for one cycle
    cycle_duration = cycle_crest_to_crest_distance / sr
    print(f"Duration of One Cycle (in seconds): {cycle_duration}")

    # If needed, convert this to physical displacement using a calibration factor
    # For now, this is just in terms of signal amplitude.
else:
    print("Not enough peaks detected for one cycle.")

import librosa
import numpy as np
import scipy.signal as signal

# Load the audio file
audio_path = 'sample.wav'  # Update the path to your audio file
y, sr = librosa.load(audio_path, sr=None)  # Load audio signal with original sampling rate

# Compute the envelope using the Hilbert transform
analytic_signal = librosa.core.hilbert(y)
amplitude_envelope = np.abs(analytic_signal)

# Normalize the envelope (optional)
amplitude_envelope = amplitude_envelope / np.max(amplitude_envelope)

# Detect peaks in the envelope to find crest-to-crest cycles
peaks, _ = signal.find_peaks(amplitude_envelope, height=0.1)  # Adjust height to filter noise

# If we have at least two peaks, calculate the distance between them (period)
if len(peaks) > 1:
    cycle_crest_to_crest_distance = np.diff(peaks)[0]  # The distance between two peaks (in samples)
    print(f"Crest-to-Crest Cycle Distance (in samples): {cycle_crest_to_crest_distance}")

    # Convert to time duration (in seconds) for one cycle
    cycle_duration = cycle_crest_to_crest_distance / sr
    print(f"Duration of One Cycle (in seconds): {cycle_duration}")

    # Cumulative displacement every second
    total_duration = len(y) / sr  # Total duration of the audio file in seconds
    displacement_per_second = []

    for second in range(int(total_duration)):
        # Calculate the number of cycles within this second
        cycles_in_second = np.floor(second / cycle_duration)  # Floor function to get full cycles in the second

        # Displacement for this second is the number of cycles times the cycle distance
        displacement_for_second = cycles_in_second * cycle_crest_to_crest_distance
        displacement_per_second.append(displacement_for_second)

    # Cumulative displacement every second
    cumulative_displacement = np.cumsum(displacement_per_second)

    # Display the cumulative displacement every second
    print("Cumulative Displacement (in samples) every second:")
    print(cumulative_displacement)

else:
    print("Not enough peaks detected for one cycle.")

import librosa
import numpy as np
import scipy.signal as signal
from scipy.signal import hilbert

# Load the audio file
audio_path = 'sample.wav'  # Update the path to your audio file
y, sr = librosa.load(audio_path, sr=None)  # Load audio signal with original sampling rate

# Compute the envelope using the Hilbert transform from scipy
analytic_signal = hilbert(y)
amplitude_envelope = np.abs(analytic_signal)

# Normalize the envelope (optional)
amplitude_envelope = amplitude_envelope / np.max(amplitude_envelope)

# Detect peaks in the envelope to find crest-to-crest cycles
peaks, _ = signal.find_peaks(amplitude_envelope, height=0.1)  # Adjust height to filter noise

# If we have at least two peaks, calculate the distance between them (period)
if len(peaks) > 1:
    cycle_crest_to_crest_distance = np.diff(peaks)[0]  # The distance between two peaks (in samples)
    print(f"Crest-to-Crest Cycle Distance (in samples): {cycle_crest_to_crest_distance}")

    # Convert to time duration (in seconds) for one cycle
    cycle_duration = cycle_crest_to_crest_distance / sr
    print(f"Duration of One Cycle (in seconds): {cycle_duration}")

    # Cumulative displacement every second
    total_duration = len(y) / sr  # Total duration of the audio file in seconds
    displacement_per_second = []

    for second in range(int(total_duration)):
        # Calculate the number of cycles within this second
        cycles_in_second = np.floor(second / cycle_duration)  # Floor function to get full cycles in the second

        # Displacement for this second is the number of cycles times the cycle distance
        displacement_for_second = cycles_in_second * cycle_crest_to_crest_distance
        displacement_per_second.append(displacement_for_second)

    # Cumulative displacement every second
    cumulative_displacement = np.cumsum(displacement_per_second)

    # Display the cumulative displacement every second
    print("Cumulative Displacement (in samples) every second:")
    print(cumulative_displacement)

else:
    print("Not enough peaks detected for one cycle.")

import librosa
import numpy as np

# Load the audio file
audio_path = 'sample.wav'  # Update with your actual audio file path
y, sr = librosa.load(audio_path, sr=None)  # Load the audio signal with the original sampling rate

# Calculate the fundamental frequency (F₀) for each frame using pyin
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Convert the audio into time intervals for every second
total_duration = len(y) / sr  # Total duration in seconds
seconds = np.arange(0, total_duration, 1)  # Create an array for each second

# Calculate speed for each second (just take the F₀ at the center of the second)
speed_per_second = []

for second in seconds:
    # Define the time interval for the second (start and end in samples)
    start_sample = int(second * sr)
    end_sample = int((second + 1) * sr)

    # Get the F₀ values for that second (you can average over the second or take a specific time point)
    f0_segment = f0[start_sample:end_sample]

    # Take the average fundamental frequency (F₀) for the second as the speed
    # We handle NaN values (where F₀ is not detected) by using np.nanmean (mean ignoring NaNs)
    avg_f0 = np.nanmean(f0_segment)  # Average F₀ for the second

    # Append the result to speed_per_second
    speed_per_second.append(avg_f0)

# Output the speed for each second
for second, speed in zip(seconds, speed_per_second):
    print(f"Second {second}: Speed = {speed}")

import librosa
import numpy as np

# Load the audio file
audio_path = 'sample.wav'  # Update with your actual audio file path
y, sr = librosa.load(audio_path, sr=None)  # Load the audio signal with the original sampling rate

# Calculate the fundamental frequency (F₀) for each frame using pyin
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Normalize F₀ to a maximum value for simplicity (optional)
f0_normalized = f0 / np.max(f0)

# Calculate phase based on the normalized F₀
# Phase can be represented as the cumulative sum of fundamental frequency values, normalized
phase = np.cumsum(f0_normalized) % 360  # Convert to a cycle of 360 degrees

# Calculate velocity based on phase: sin(phase) gives direction (positive for outward, negative for inward)
velocity = np.sin(np.radians(phase)) * f0_normalized  # Convert phase to radians for sin()

# Output velocity for every second (taking average velocity per second)
time_per_second = len(y) // sr
velocity_per_second = []

for second in range(time_per_second):
    start = second * sr
    end = (second + 1) * sr
    velocity_per_second.append(np.mean(velocity[start:end]))

# Print the velocity for each second
for second, velocity in enumerate(velocity_per_second):
    print(f"Second {second}: Velocity = {velocity}")

f0_per_second = np.nan_to_num(f0_per_second)

print("Sample of raw F0 values:", f0[:10])

import librosa
import numpy as np

# Load audio
audio_path = 'sample.wav'
y, sr = librosa.load(audio_path, sr=None)

# Check basic stats about the audio
print("Audio duration (seconds):", len(y) / sr)
print("Sampling rate:", sr)

# Try a wider pitch range for F0 detection
f0, voiced_flag, _ = librosa.pyin(y,
                                  fmin=librosa.note_to_hz('C1'),  # Lower boundary
                                  fmax=librosa.note_to_hz('C8'),  # Higher boundary
                                  sr=sr)

print("Sample of raw F0 values:", f0[:10])
print("Number of detected F0 values:", np.sum(~np.isnan(f0)))

import librosa
import numpy as np

# Load audio
audio_path = 'sample.wav'  # Replace with your actual file
y, sr = librosa.load(audio_path, sr=None)

# Check basic stats about the audio
duration = len(y) / sr
print("Audio duration (seconds):", duration)
print("Sampling rate:", sr)

# Try a wider pitch range for F0 detection
f0, voiced_flag, _ = librosa.pyin(y,
                                  fmin=librosa.note_to_hz('C1'),  # Lower boundary
                                  fmax=librosa.note_to_hz('C8'),  # Higher boundary
                                  sr=sr)

# Replace nan values with zeros
f0 = np.nan_to_num(f0, nan=0)  # or use interpolation if preferred

# Calculate speed as sum of frequencies each second
speed_per_second = np.array([np.sum(f0[i:i+sr]) for i in range(0, len(f0), sr)])  # Speed for each second

# Print speed for first 10 seconds
print("Speed per second (sample of first 10 seconds):", speed_per_second[:10])

# Continue with other calculations as needed

from pydub import AudioSegment
import numpy as np

audio_path = 'sample.wav'
audio = AudioSegment.from_wav(audio_path)

# Convert to numpy array
samples = np.array(audio.get_array_of_samples(), dtype=float)

# Now you can proceed with further analysis

audio_path = 'sample.wav'

audio_path = '/path/to/your/file/sample.wav'  # Replace with actual path

import os
print(os.getcwd())

audio_path = 'sample.wav'  # Make sure the file is in the same directory

audio_path = 'subfolder/sample.wav'  # Adjust the folder name accordingly

audio_path = '/full/path/to/your/sample.wav'  # Replace with the full path

import os
print(os.path.splitext(audio_path))  # It will print the file name and extension

import os
print(os.access(audio_path, os.R_OK))  # Should return True if the file is readable

import librosa

# Update with your correct file path
audio_path = 'sample.wav'

# Load the audio file
try:
    y, sr = librosa.load(audio_path, sr=None)
    print("Audio loaded successfully")
except Exception as e:
    print(f"Error loading audio: {e}")

audio_path = '/content/sample.wav'  # Ensure this is correct for Colab

audio_path = '/content/sample.wav'  # Adjust the path if necessary

import librosa
import numpy as np

# Load audio
audio_path = 'sample.wav'  # Replace with your file path
y, sr = librosa.load(audio_path, sr=None)

# Check basic stats about the audio
print("Audio duration (seconds):", len(y) / sr)
print("Sampling rate:", sr)

# Try a wider pitch range for F0 detection
f0, voiced_flag, _ = librosa.pyin(y,
                                  fmin=librosa.note_to_hz('C1'),  # Lower boundary
                                  fmax=librosa.note_to_hz('C8'),  # Higher boundary
                                  sr=sr)

print("Sample of raw F0 values:", f0[:10])
print("Number of detected F0 values:", np.sum(~np.isnan(f0)))

import numpy as np

# Example of cumulative displacement (you would replace this with your actual data)
cumulative_displacements = np.array([10, 20, 30, 45, 60, 75, 90, 105, 120])

# Calculate displacement made every second
displacements = np.diff(cumulative_displacements)

# Include the first value as it corresponds to the displacement at second 1
displacements = np.insert(displacements, 0, cumulative_displacements[0])

print(displacements)

import numpy as np

# Example: You should already have your 'F0' array (fundamental frequencies over time)
# For example, let's assume 'F0_values' is a numpy array with 678 seconds of F0 data.

# Make sure 'F0_values' contains F0 at each second.
F0_values = np.array([100, 105, 110, 120, 125, 130, 140, 145, 150])  # Example data, replace with real F0

# Compute displacement (difference between consecutive F0 values)
displacement = np.diff(F0_values)

# If needed, you can append a 0 for the first second
displacement_per_second = np.insert(displacement, 0, 0)

# Now 'displacement_per_second' contains the displacement for each second
print(displacement_per_second)

import numpy as np

# Assuming F0_values is the array that contains the fundamental frequencies for 678 seconds.
# Example: Let's create an array with F0 values for 678 seconds (replace with your actual F0 data).
F0_values = np.random.uniform(100, 200, 678)  # Example random data; replace this with your actual F0 values.

# Ensure F0_values is a numpy array
F0_values = np.array(F0_values)

# Calculate displacement by finding the difference between consecutive seconds
displacement_per_second = np.diff(F0_values)  # Difference between consecutive F0 values

# If you want to insert zero displacement for the first second
displacement_per_second = np.insert(displacement_per_second, 0, 0)

# Now displacement_per_second will contain the displacement per second
print(displacement_per_second)

import numpy as np

# Example: Replace with your actual F0 values for 678 seconds.
F0_values = np.random.uniform(100, 200, 678)  # Replace this with your actual F0 data

# Create an array of seconds (from 1 to 678)
seconds = np.arange(1, len(F0_values) + 1)

# Calculate displacement by finding the difference between consecutive F0 values
displacement_per_second = np.diff(F0_values)  # Difference between consecutive F0 values

# Insert 0 at the start for the first second (since there's no displacement at time 0)
displacement_per_second = np.insert(displacement_per_second, 0, 0)

# Now create a list of tuples, each containing (second, displacement)
displacement_with_seconds = list(zip(seconds, displacement_per_second))

# Output the displacement with corresponding second
for second, displacement in displacement_with_seconds:
    print(f"Second: {second}, Displacement: {displacement}")

import numpy as np
import librosa
import matplotlib.pyplot as plt

# Load the audio file (make sure the path to your audio file is correct)
audio_file = 'sample.wav'  # Replace with your file path
y, sr = librosa.load(audio_file, sr=None)

# Extract the fundamental frequency (F0) over time using librosa's piptrack
# This function returns the frequency (F0) over time
_, freq = librosa.core.piptrack(y=y, sr=sr)

# Get the F0 frequencies at each frame
f0 = []
for t in range(freq.shape[1]):
    f0_frame = freq[:, t]
    f0_frame = f0_frame[f0_frame > 0]  # Filter out 0 values
    if len(f0_frame) > 0:
        f0.append(np.max(f0_frame))  # Choose the maximum frequency (F0) in the frame

# Convert F0 list to a numpy array for easier manipulation
f0 = np.array(f0)

# Calculate speed as the number of cycles per second
# To calculate speed, we need to count the number of F0 cycles in each second

# Create a time array to match F0 values
time = np.linspace(0, len(f0)/sr, len(f0))

# Plot F0 to visualize the frequency variation over time
plt.figure(figsize=(10, 6))
plt.plot(time, f0)
plt.xlabel('Time (s)')
plt.ylabel('Fundamental Frequency (Hz)')
plt.title('Fundamental Frequency (F0) Over Time')
plt.show()

# Speed in vocalics is the F0 value per second (essentially F0 in Hz)
# So we already have the speed in cycles per second as F0 itself
# To get the speed for each second, let's round it or use the average for each second:

# Calculate speed every second
speed_per_second = []
for i in range(int(len(f0)/sr)):
    start_idx = i * sr
    end_idx = (i + 1) * sr
    speed_per_second.append(np.mean(f0[start_idx:end_idx]))  # Calculate average F0 (speed) per second

# Print the speed (in cycles per second) for each second
print("Speed in vocalics (cycles per second) for each second:")
for second, speed in enumerate(speed_per_second):
    print(f"Second {second+1}: {speed} Hz")

audio_file = 'sample.wav'

audio_file = '/path/to/your/folder/sample.wav'  # Replace with the correct path

import librosa
import numpy as np

# Load the audio file
audio_file = '/path_to_your_audio_file/sample.wav'  # replace with your file path
y, sr = librosa.load(audio_file, sr=None)

# Use librosa to extract the F0 (fundamental frequency)
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Generate time intervals (seconds) corresponding to the F0 frames
frame_times = librosa.times_like(f0, sr=sr)

# Resample F0 values to get an estimate every second
# Create a list of time indices at every second
seconds = np.arange(0, len(frame_times) / sr, 1)  # time intervals at every second

# Create an empty list to hold the speeds at each second
speeds = []

# Loop through each second and calculate the speed (F0 per second)
for second in seconds:
    # Find the closest frame time to the current second
    idx = np.abs(frame_times - second).argmin()

    # Calculate speed by looking at F0 at this second (or between frames)
    if idx > 0 and not np.isnan(f0[idx]):
        # Calculate speed (inverse of time interval between frames)
        time_interval = frame_times[idx] - frame_times[idx-1]  # time between frames
        speed = 1 / time_interval if time_interval != 0 else 0
        speeds.append(speed)
    else:
        speeds.append(0)

# Now speeds contains the speed at each second
print(speeds[:10])  # Display first 10 seconds of speed values

import os

audio_file = 'path_to_your_audio_file/sample.wav'  # Ensure the correct path

# Check if the file exists
if os.path.exists(audio_file):
    print("File found!")
else:
    print("File not found. Please check the path.")

from google.colab import files
uploaded = files.upload()  # This will prompt you to upload the file

# After uploading, check if the file exists
import os
if os.path.exists('sample.wav'):
    print("File found!")
else:
    print("File not found.")

import librosa
import numpy as np

# Load the audio file
audio_file = '/path_to_your_audio_file/sample.wav'  # replace with your file path
y, sr = librosa.load(audio_file, sr=None)

# Use librosa to extract the F0 (fundamental frequency)
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Generate time intervals (seconds) corresponding to the F0 frames
frame_times = librosa.times_like(f0, sr=sr)

# Resample F0 values to get an estimate every second
# Create a list of time indices at every second
seconds = np.arange(0, len(frame_times) / sr, 1)  # time intervals at every second

# Create an empty list to hold the speeds at each second
speeds = []

# Loop through each second and calculate the speed (F0 per second)
for second in seconds:
    # Find the closest frame time to the current second
    idx = np.abs(frame_times - second).argmin()

    # Calculate speed by looking at F0 at this second (or between frames)
    if idx > 0 and not np.isnan(f0[idx]):
        # Calculate speed (inverse of time interval between frames)
        time_interval = frame_times[idx] - frame_times[idx-1]  # time between frames
        speed = 1 / time_interval if time_interval != 0 else 0
        speeds.append(speed)
    else:
        speeds.append(0)

# Now speeds contains the speed at each second
print(speeds[:10])  # Display first 10 seconds of speed values

import os

audio_file = '/content/drive/MyDrive/your_folder/sample.wav'
if os.path.exists(audio_file):
    print("File exists and is accessible!")
else:
    print("File path error!")

!ls /content/

audio_file = '/content/sample.wav'

import os

audio_file = '/content/sample.wav'  # Adjust according to where you see the file
if os.path.exists(audio_file):
    print("File exists and is accessible!")
else:
    print("File path error!")

print(f"Loading file from: {audio_file}")  # Check the file path
y, sr = librosa.load(audio_file, sr=None)

with open(audio_file, 'rb') as f:
    print("File opened successfully!")

print(f"Loading file from: {audio_file}")
y, sr = librosa.load(audio_file, sr=None)

import os
print(f"Current working directory: {os.getcwd()}")

audio_file = '/content/sample.wav'

import librosa
import numpy as np

# Load the audio file
audio_file = '/content/sample.wav'  # Update to the correct file path
y, sr = librosa.load(audio_file, sr=None)

# Use librosa to extract the F0 (fundamental frequency)
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Generate time intervals (seconds) corresponding to the F0 frames
frame_times = librosa.times_like(f0, sr=sr)

# Create a list of time indices at every second
seconds = np.arange(0, len(frame_times) / sr, 1)  # time intervals at every second

# Create an empty list to hold the speeds at each second
speeds = []

# Loop through each second and calculate the speed (F0 per second)
for second in seconds:
    # Find the closest frame time to the current second
    idx = np.abs(frame_times - second).argmin()

    # Calculate speed by looking at F0 at this second (or between frames)
    if idx > 0 and not np.isnan(f0[idx]):
        # Calculate speed (inverse of time interval between frames)
        time_interval = frame_times[idx] - frame_times[idx-1]  # time between frames
        speed = 1 / time_interval if time_interval != 0 else 0
        speeds.append(speed)
    else:
        speeds.append(0)

# Now speeds contains the speed at each second
print(speeds[:10])  # Display first 10 seconds of speed values

import numpy as np

# Assuming you already have a list of displacement values (displacements)
displacements = [10, 15, 15, 20, 25, 30, 30, 35, 40]  # Example displacements at each second
time_intervals = 1  # Time interval between each second is 1 second

# Calculate the speed at each second (difference in displacement per second)
speeds = []

for i in range(1, len(displacements)):
    # Calculate the speed as the difference in displacement divided by time
    speed = (displacements[i] - displacements[i-1]) / time_intervals
    speeds.append(speed)

# Now speeds contains the speed at each second
print(speeds)

import numpy as np

# Example displacement values for every second (replace with your actual displacement data for 678 seconds)
# Assuming you have 678 displacement values for each second
displacement = np.random.rand(678)  # Replace this with your displacement array (e.g., from previous calculations)

# Calculate speed by taking the difference of displacement between consecutive seconds
speed = np.diff(displacement)

# Append zero for the first second (since we have no previous displacement to compare)
speed = np.insert(speed, 0, 0)

# Display the speed at every second
print("Speed every second:", speed[:10])  # Display the first 10 speed values for example

import numpy as np

# Let's assume 'displacement' is the list of displacement values you have for each second
# If displacement is already available as a numpy array, you can use it directly

# For example, displacement array (just for illustration, replace with your actual data)
displacement = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])  # Example displacement values

# Calculate the speed for each second (the change in displacement between consecutive seconds)
speed = np.diff(displacement)

# To match the speed array to seconds 1 to 678, we need to append a 0 at the start (for the first second)
speed = np.insert(speed, 0, 0)

# Create a list of seconds from 1 to 678
seconds = np.arange(1, len(speed) + 1)

# Combine seconds with corresponding speed values
seconds_and_speeds = list(zip(seconds, speed))

# Display first 10 pairs of seconds and their corresponding speed
print("Seconds and corresponding speed:", seconds_and_speeds[:10])

Seconds and corresponding speeds: [(1, speed_at_second_1), (2, speed_at_second_2), ..., (10, speed_at_second_10)]

import numpy as np

# Example displacement values for each second (replace with your actual displacement values)
displacement = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])  # Example displacement data

# Calculate the speed for each second (change in displacement)
speed = np.diff(displacement)  # This gives the difference between consecutive displacements

# Insert 0 at the beginning, because at second 1, there is no previous displacement to compare
speed = np.insert(speed, 0, 0)

# Create a list of seconds from 1 to the length of the displacement data
seconds = np.arange(1, len(displacement) + 1)

# Now, we'll have seconds and the corresponding speeds
# Just ensure both have the same length and pair them up properly
seconds_and_speeds = list(zip(seconds, speed))

# Display the first 10 seconds and their corresponding speeds
print("Seconds and corresponding speeds:", seconds_and_speeds[:10])

import numpy as np

# Example displacement values for each second (replace with your actual displacement values)
displacement = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])  # Example displacement data

# Calculate the speed for each second (change in displacement)
speed = np.diff(displacement)  # This gives the difference between consecutive displacements

# Insert 0 at the beginning, because at second 1, there is no previous displacement to compare
speed = np.insert(speed, 0, 0)

# Create a list of seconds from 1 to the length of the displacement data
seconds = np.arange(1, len(displacement) + 1)

# Display seconds and their corresponding speeds in the required format
for sec, spd in zip(seconds, speed):
    print(f"Second {sec} = Speed: {spd}")

import numpy as np

# Example: Replace this with your actual displacement values (for 678 seconds)
displacement = np.array([10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70])  # Example data

# Ensure displacement has 678 values
assert len(displacement) == 678, "Displacement data must have 678 values."

# Calculate speed for each second (change in displacement)
speed = np.diff(displacement)  # Difference between consecutive displacements

# Insert 0 at the beginning because at second 1, there's no previous displacement to compare
speed = np.insert(speed, 0, 0)

# Create a list of seconds from 1 to 678
seconds = np.arange(1, 679)

# Display seconds and corresponding speeds
for sec, spd in zip(seconds, speed):
    print(f"Second {sec} = Speed: {spd}")

print(f"Displacement data length: {len(displacement)}")

# Check the length of the displacement data
print(f"Displacement data length: {len(displacement)}")

# If the length is indeed 678, we can calculate the speed as the change in displacement
# Speed calculation (change in displacement per second)
speeds = np.diff(displacement)  # Calculate the difference between consecutive values

# Extend the speed array to match 678 seconds (adding 0 for the first second)
speeds = np.insert(speeds, 0, 0)  # Assuming speed is 0 for the first second

# Now speeds contains the speed for each second
print(f"Speeds for each second: {speeds[:10]}")  # Display the first 10 speeds to check

# Check the displacement array's length
print(f"Displacement data length: {len(displacement)}")

import librosa
import numpy as np

# Load the audio file
audio_file = '/path_to_your_audio_file/sample.wav'  # replace with your file path
y, sr = librosa.load(audio_file, sr=None)

# Use librosa to extract the F0 (fundamental frequency)
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('C8'))

# Generate time intervals (seconds) corresponding to the F0 frames
frame_times = librosa.times_like(f0, sr=sr)

# Resample F0 values to get an estimate every second
# Create a list of time indices at every second
seconds = np.arange(0, len(frame_times) / sr, 1)  # time intervals at every second

# Create an empty list to hold the speeds at each second (using F0 as speed)
speeds = []

# Loop through each second and calculate the speed (F0 per second)
for second in seconds:
    # Find the closest frame time to the current second
    idx = np.abs(frame_times - second).argmin()

    # If the F0 value at that second exists, add it to speeds list
    if not np.isnan(f0[idx]):
        speeds.append(f0[idx])
    else:
        speeds.append(0)  # If F0 is NaN, set speed to 0

# Now speeds contains the F0 values (speed in vocalics) at each second
# You will get the speed at each second (in Hz)
for i in range(len(speeds)):
    print(f"Second {i+1}: Speed = {speeds[i]} Hz")

import os

# Check the current working directory
print("Current working directory:", os.getcwd())

from google.colab import files
uploaded = files.upload()  # This will prompt you to upload the file

import os

# Print the current directory and list files
print("Current working directory:", os.getcwd())
print("Files in the current directory:", os.listdir())

# Use the correct file name
audio_file = 'sample.wav'  # Or 'sample (1).wav' if you want that one

# Load the audio file
y, sr = librosa.load(audio_file, sr=None)

import numpy as np

# Example displacement array with 678 values (Replace this with your actual displacement data)
# Here, displacement is just a sample, your actual displacement data should go here
displacement = np.random.randn(678)  # Replace with your actual displacement data

# Ensure displacement has 678 values
assert len(displacement) == 678, "Displacement data must have 678 values."

# Calculate speed for each second (change in displacement)
speeds = np.diff(displacement)  # Calculate the difference between consecutive displacements

# Add a zero for the first second since there's no previous displacement to calculate speed
speeds = np.insert(speeds, 0, 0)

# Print out speed for each second
for second, speed in enumerate(speeds, start=1):
    print(f"Second {second}: speed: {speed:.6f}")

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Calculate displacement and velocity every second
displacements = []
velocities = []
for second in range(1, int(duration) + 1):
    # Get the amplitude at the start and end of the second
    start_sample = int((second - 1) * sr)
    end_sample = int(second * sr)
    amplitude_start = y[start_sample]
    amplitude_end = y[end_sample]

    # Calculate displacement as the difference in amplitude
    displacement = amplitude_end - amplitude_start
    displacements.append(displacement)

    # Calculate velocity as displacement divided by time (1 second)
    velocity = displacement / 1.0  # Time interval is 1 second
    velocities.append(velocity)

# Print results
for second, (disp, vel) in enumerate(zip(displacements, velocities), start=1):
    print(f"Second {second}: Displacement = {disp:.4f}, Velocity = {vel:.4f} units/s")

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0 = librosa.pyin(y, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))[0]  # Extract F0
f0 = np.nan_to_num(f0, nan=0.0)  # Replace NaN values with 0

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Example data (replace with your actual values)
# For demonstration, let's assume:
# - velocities = displacement per second
velocities = np.random.uniform(0, 1, int(duration))  # Random velocities

# Calculate mass proxy from F0
epsilon = 1e-6  # Small constant to avoid division by zero
mass_proxy = 1 / (np.array(f0_per_second) + epsilon)  # Mass proxy = 1 / F0

# Calculate momentum every second
momenta = []
for second in range(int(duration)):
    # Get mass proxy and velocity for the current second
    mass = mass_proxy[second]
    velocity = velocities[second]

    # Calculate momentum
    momentum = mass * velocity
    momenta.append(momentum)

# Print results
for second, momentum in enumerate(momenta, start=1):
    print(f"Second {second}: Momentum = {momentum:.4f}")







audio_file = 'path/to/your/sample.wav'

audio_file = '/full/path/to/your/sample.wav'

from google.colab import files
uploaded = files.upload()

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0 = librosa.pyin(y, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))[0]  # Extract F0
f0 = np.nan_to_num(f0, nan=0.0)  # Replace NaN values with 0

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Example data (replace with your actual values)
# For demonstration, let's assume:
# - velocities = displacement per second
velocities = np.random.uniform(0, 1, int(duration))  # Random velocities

# Calculate mass proxy from F0
epsilon = 1e-6  # Small constant to avoid division by zero
mass_proxy = 1 / (np.array(f0_per_second) + epsilon)  # Mass proxy = 1 / F0

# Calculate momentum every second
momenta = []
for second in range(int(duration)):
    # Get mass proxy and velocity for the current second
    mass = mass_proxy[second]
    velocity = velocities[second]

    # Calculate momentum
    momentum = mass * velocity
    momenta.append(momentum)

# Print results
for second, momentum in enumerate(momenta, start=1):
    print(f"Second {second}: Momentum = {momentum:.4f}")

import numpy as np

# Example data (replace with your actual velocity values)
# For demonstration, let's assume velocities are calculated as displacement per second
velocities = np.random.uniform(0, 1, 678)  # Random velocities for 678 seconds

# Calculate acceleration every second
accelerations = []
for second in range(1, len(velocities)):
    # Calculate change in velocity
    delta_v = velocities[second] - velocities[second - 1]
    accelerations.append(delta_v)

# Add a placeholder for the first second (no previous velocity to compare)
accelerations.insert(0, 0.0)  # Acceleration at second 1 is 0

# Print results
for second, acceleration in enumerate(accelerations, start=1):
    print(f"Second {second}: Acceleration = {acceleration:.4f} units/s²")

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0 = librosa.pyin(y, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))[0]  # Extract F0
f0 = np.nan_to_num(f0, nan=0.0)  # Replace NaN values with 0

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Extract amplitude (height) for each second
amplitudes = []
for second in range(int(duration)):
    start_sample = int(second * sr)
    end_sample = int((second + 1) * sr)
    amplitude = np.mean(np.abs(y[start_sample:end_sample]))  # Average amplitude for the second
    amplitudes.append(amplitude)

# Calculate potential energy every second
potential_energies = []
for second in range(int(duration)):
    # Get mass proxy (F0) and amplitude (height) for the current second
    mass = 1 / (f0_per_second[second] + 1e-6)  # Mass proxy = 1 / F0
    height = amplitudes[second]  # Amplitude as height

    # Calculate potential energy
    pe = mass * height
    potential_energies.append(pe)

# Print results
for second, pe in enumerate(potential_energies, start=1):
    print(f"Second {second}: Potential Energy = {pe:.4f}")

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0 = librosa.pyin(y, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))[0]  # Extract F0
f0 = np.nan_to_num(f0, nan=0.0)  # Replace NaN values with 0

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Example data (replace with your actual velocity values)
# For demonstration, let's assume velocities are calculated as displacement per second
velocities = np.random.uniform(0, 1, int(duration))  # Random velocities for 678 seconds

# Calculate kinetic energy every second
kinetic_energies = []
for second in range(int(duration)):
    # Get mass proxy (F0) and velocity for the current second
    mass = 1 / (f0_per_second[second] + 1e-6)  # Mass proxy = 1 / F0
    velocity = velocities[second]  # Velocity for the current second

    # Calculate kinetic energy
    ke = 0.5 * mass * velocity**2
    kinetic_energies.append(ke)

# Print results
for second, ke in enumerate(kinetic_energies, start=1):
    print(f"Second {second}: Kinetic Energy = {ke:.4f}")

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0 = librosa.pyin(y, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))[0]  # Extract F0
f0 = np.nan_to_num(f0, nan=0.0)  # Replace NaN values with 0

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Calculate inertia every second
epsilon = 1e-6  # Small constant to avoid division by zero
inertias = []
for second in range(int(duration)):
    # Get F0 for the current second
    f0_value = f0_per_second[second]

    # Calculate inertia
    inertia = 1 / (f0_value + epsilon)
    inertias.append(inertia)

# Print results
for second, inertia in enumerate(inertias, start=1):
    print(f"Second {second}: Inertia = {inertia:.4f}")

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0 = librosa.pyin(y, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))[0]  # Extract F0
f0 = np.nan_to_num(f0, nan=0.0)  # Replace NaN values with 0

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Example data (replace with your actual velocity values)
# For demonstration, let's assume velocities are calculated as displacement per second
velocities = np.random.uniform(0, 1, int(duration))  # Random velocities for 678 seconds

# Calculate impulse every second
epsilon = 1e-6  # Small constant to avoid division by zero
impulses = []
for second in range(1, int(duration)):
    # Get mass proxy (F0) for the current second
    mass = 1 / (f0_per_second[second] + epsilon)  # Mass proxy = 1 / F0

    # Calculate change in velocity
    delta_v = velocities[second] - velocities[second - 1]

    # Calculate impulse
    impulse = mass * delta_v
    impulses.append(impulse)

# Add a placeholder for the first second (no previous velocity to compare)
impulses.insert(0, 0.0)  # Impulse at second 1 is 0

# Print results
for second, impulse in enumerate(impulses, start=1):
    print(f"Second {second}: Impulse = {impulse:.4f}")

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame using librosa.pyin
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))

# Replace NaN values in F0 with interpolation or a valid value, if needed
f0 = np.nan_to_num(f0, nan=0.0)  # Replace NaN with 0, or you can interpolate for better results

# Average F0 values to get one F0 value per second
f0_per_second = []
hop_length = len(f0) // duration  # Calculate hop length per second

for second in range(int(duration)):
    start_frame = int(second * hop_length)  # Convert to integer
    end_frame = int((second + 1) * hop_length)  # Convert to integer
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Print the F0 values for each second
for second, f0_value in enumerate(f0_per_second, start=1):
    print(f"Second {second}: F0 = {f0_value:.4f} Hz")

import numpy as np

# Ensure F0_values and velocities are correctly defined from previous steps
# F0_values: list of F0 values per second (one value per second)
# velocities: list of velocities per second (one value per second)

# Calculate momentum: p = (1 / F0) * v
# To avoid division by zero errors, we'll check for F0 = 0 and set momentum to 0 in such cases
momentum = [v / F0 if F0 != 0 else 0 for F0, v in zip(F0_values, velocities)]

# Display the calculated momenta
print("Momentum per second:", momentum)

print("F0 values:", F0_values[:10])  # Show the first 10 F0 values
print("Velocities:", velocities[:10])  # Show the first 10 velocities

# Commented out IPython magic to ensure Python compatibility.
# %whos

# Ensure F0_values and velocities are saved for later use
F0_values = F0_values  # or whatever variable holds your F0 results
velocities = velocities  # or whatever variable holds your velocities

# Store F0 values and velocities explicitly
F0_values = your_F0_variable_name  # Replace with the actual name
velocities = your_velocity_variable_name  # Replace with the actual name

print("Saved F0 values:", F0_values[:10])
print("Saved velocities:", velocities[:10])

import numpy as np

# Ensure F0_values and velocities are correctly defined from previous steps
# F0_values: list of F0 values per second (one value per second)
# velocities: list of velocities per second (one value per second)

# Calculate momentum: p = (1 / F0) * v
# To avoid division by zero errors, we'll check for F0 = 0 and set momentum to 0 in such cases
momentum = [v / F0 if F0 != 0 else 0 for F0, v in zip(F0_values, velocities)]

# Display the calculated momenta
print("Momentum per second:", momentum)

import librosa

# Load the audio file
audio_file = 'sample.wav'  # Change this to your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

from google.colab import drive
drive.mount('/content/drive')

audio_file = '/content/drive/MyDrive/sample.wav'  # Update with the correct path to your file

import librosa
import numpy as np

# Load the audio file from Google Drive
y, sr = librosa.load(audio_file, sr=None)

# Use librosa's `pyin` for pitch tracking (F0 calculation)
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('B8'))

# Calculate F0 per second
seconds = int(len(f0) / sr)  # Number of seconds
F0_values = [np.mean(f0[i*sr:(i+1)*sr]) for i in range(seconds)]

# Print the first 10 F0 values
print("F0 values per second:", F0_values[:10])

# Replace NaN values with 0 (or you could use np.nanmean to replace with mean of valid values)
f0 = np.nan_to_num(f0, nan=0)

# Calculate F0 per second
seconds = int(len(f0) / sr)  # Number of seconds
F0_values = [np.mean(f0[i*sr:(i+1)*sr]) for i in range(seconds)]

# Print the first 10 F0 values
print("F0 values per second:", F0_values[:10])

import librosa
import numpy as np

# Load the audio file from Google Drive
y, sr = librosa.load(audio_file, sr=None)

# Use librosa's `pyin` for pitch tracking (F0 calculation)
f0, voiced_flag, voiced_probs = librosa.pyin(y, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('B8'))

# Handle NaN values by replacing them with 0 (or another approach)
f0 = np.nan_to_num(f0, nan=0)

# Number of seconds in the audio
seconds = int(len(f0) / sr)

# Calculate F0 per second
F0_values = [np.mean(f0[i*sr:(i+1)*sr]) for i in range(seconds)]

# Print out the F0 values per second
print("F0 values per second:", F0_values[:10])

import librosa
import numpy as np

# Load the audio file from Google Drive
audio_file = '/content/drive/MyDrive/sample.wav'  # Update this with your correct file path
y, sr = librosa.load(audio_file, sr=None)

# Total number of seconds in the audio
seconds = int(len(y) / sr)

# Initialize list for storing F0 values per second
F0_values = []

# Process each second of the audio
for i in range(seconds):
    start_idx = i * sr  # Start of the second
    end_idx = (i + 1) * sr  # End of the second
    y_segment = y[start_idx:end_idx]  # Get audio segment for the current second

    # Extract pitch (F0) for the segment using librosa
    f0, voiced_flag, voiced_probs = librosa.pyin(y_segment, fmin=librosa.note_to_hz('C1'), fmax=librosa.note_to_hz('B8'))

    # Handle NaN values by replacing them with 0 (or another approach)
    f0 = np.nan_to_num(f0, nan=0)

    # Calculate the mean F0 for this segment and append it to the list
    F0_values.append(np.mean(f0))

# Print out the first 10 F0 values per second
print("F0 values per second:", F0_values[:10])

from google.colab import drive
drive.mount('/content/drive')

import numpy as np
import librosa  # Library for audio analysis

# Load the audio file
audio_file = "sample.wav"  # Replace with your audio file path
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0, voiced_flag, voiced_probs = librosa.pyin(
    y,
    fmin=librosa.note_to_hz('C2'),  # Minimum frequency (e.g., C2 = 65.41 Hz)
    fmax=librosa.note_to_hz('C7')   # Maximum frequency (e.g., C7 = 2093 Hz)
)

# Replace NaN values with 0 (unvoiced frames)
f0 = np.nan_to_num(f0, nan=0.0)

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Print results
for second, f0_value in enumerate(f0_per_second, start=1):
    print(f"Second {second}: F0 = {f0_value:.2f} Hz")

import numpy as np
import librosa
from google.colab import drive

# Mount Google Drive
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/path/to/your/sample.wav"  # Update this path

# Load the audio file
y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0, voiced_flag, voiced_probs = librosa.pyin(
    y,
    fmin=librosa.note_to_hz('C2'),  # Minimum frequency (e.g., C2 = 65.41 Hz)
    fmax=librosa.note_to_hz('C7')   # Maximum frequency (e.g., C7 = 2093 Hz)
)

# Replace NaN values with 0 (unvoiced frames)
f0 = np.nan_to_num(f0, nan=0.0)

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Print results
for second, f0_value in enumerate(f0_per_second, start=1):
    print(f"Second {second}: F0 = {f0_value:.2f} Hz")

/content/drive/My Drive/audio_files/sample.wav

/content/drive/My Drive/sample

import numpy as np
import librosa
from google.colab import drive

# Mount Google Drive (already mounted, so no need to remount)
# drive.mount("/content/drive")  # Uncomment if you need to remount

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update this if the file has a different name or extension

# Load the audio file
try:
    y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0, voiced_flag, voiced_probs = librosa.pyin(
    y,
    fmin=librosa.note_to_hz('C2'),  # Minimum frequency (e.g., C2 = 65.41 Hz)
    fmax=librosa.note_to_hz('C7')   # Maximum frequency (e.g., C7 = 2093 Hz)
)

# Replace NaN values with 0 (unvoiced frames)
f0 = np.nan_to_num(f0, nan=0.0)

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Print results
for second, f0_value in enumerate(f0_per_second, start=1):
    print(f"Second {second}: F0 = {f0_value:.2f} Hz")

import numpy as np
import librosa
from google.colab import drive
import os

# Mount Google Drive (already mounted, so no need to remount)
# drive.mount("/content/drive")  # Uncomment if you need to remount

# Debugging: List files in Google Drive to verify the file path
print("Listing files in Google Drive:")
print(os.listdir("/content/drive/My Drive"))

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update this with the correct path

# Debugging: Check if the file exists
if not os.path.exists(audio_file):
    print(f"File not found: {audio_file}")
    print("Please verify the file name and path.")
else:
    print(f"File found: {audio_file}")

# Load the audio file
try:
    y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0, voiced_flag, voiced_probs = librosa.pyin(
    y,
    fmin=librosa.note_to_hz('C2'),  # Minimum frequency (e.g., C2 = 65.41 Hz)
    fmax=librosa.note_to_hz('C7')   # Maximum frequency (e.g., C7 = 2093 Hz)
)

# Replace NaN values with 0 (unvoiced frames)
f0 = np.nan_to_num(f0, nan=0.0)

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Print results
for second, f0_value in enumerate(f0_per_second, start=1):
    print(f"Second {second}: F0 = {f0_value:.2f} Hz")

import numpy as np
import librosa
from google.colab import drive
import os

# Mount Google Drive (already mounted, so no need to remount)
# drive.mount("/content/drive")  # Uncomment if you need to remount

# Debugging: List files in Google Drive to verify the file path
print("Listing files in Google Drive:")
drive_contents = os.listdir("/content/drive/My Drive")
print(drive_contents)

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update this with the correct path

# Debugging: Check if the file exists
if not os.path.exists(audio_file):
    print(f"File not found: {audio_file}")
    print("Please verify the file name and path.")
    print("Here are the files in Google Drive:")
    for item in drive_contents:
        print(item)
else:
    print(f"File found: {audio_file}")

# Load the audio file
try:
    y, sr = librosa.load(audio_file, sr=None)  # y = audio data, sr = sample rate
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Calculate the time duration of the audio
duration = len(y) / sr  # Total duration in seconds

# Extract F0 (fundamental frequency) for each frame
f0, voiced_flag, voiced_probs = librosa.pyin(
    y,
    fmin=librosa.note_to_hz('C2'),  # Minimum frequency (e.g., C2 = 65.41 Hz)
    fmax=librosa.note_to_hz('C7')   # Maximum frequency (e.g., C7 = 2093 Hz)
)

# Replace NaN values with 0 (unvoiced frames)
f0 = np.nan_to_num(f0, nan=0.0)

# Average F0 values to get one F0 value per second
f0_per_second = []
frames_per_second = int(len(f0) / duration)  # Frames per second
for second in range(int(duration)):
    start_frame = second * frames_per_second
    end_frame = (second + 1) * frames_per_second
    f0_second = np.mean(f0[start_frame:end_frame])  # Average F0 for the second
    f0_per_second.append(f0_second)

# Print results
for second, f0_value in enumerate(f0_per_second, start=1):
    print(f"Second {second}: F0 = {f0_value:.2f} Hz")

import os

# Double-check the path using absolute references
file_path = "/content/drive/My Drive/sample.wav"

# Confirm if the file actually exists at the path
if os.path.exists(file_path):
    print(f"File found at: {file_path}")
else:
    print("File not found. Double-check Google Drive mount or file path.")

from google.colab import drive
drive.mount('/content/drive', force_remount=True)

import os

# List all files in your Google Drive root directory
drive_contents = os.listdir('/content/drive/My Drive')
print("Files in My Drive:", drive_contents)

# Check if 'sample.wav' is in the list
file_path = '/content/drive/My Drive/sample.wav'
if os.path.exists(file_path):
    print("✅ File found:", file_path)
else:
    print("❌ File not found. Double-check the file name and path.")

import librosa
import numpy as np

# Load the audio file
audio_file = '/content/drive/My Drive/sample.wav'
y, sr = librosa.load(audio_file, sr=None)

# Calculate the duration of the audio in seconds
duration = int(librosa.get_duration(y=y, sr=sr))

# Define window size (1 second) and hop size (1 second)
window_size = sr  # samples per second
hop_size = sr     # 1-second step

# Initialize F0 list
F0_values_per_second = []

# Calculate F0 every second
for start in range(0, len(y), hop_size):
    end = min(start + window_size, len(y))
    frame = y[start:end]
    if len(frame) < window_size:
        break  # Skip incomplete last second if any
    f0, voiced_flag, _ = librosa.pyin(frame, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))
    mean_f0 = np.nanmean(f0) if np.any(np.isfinite(f0)) else 0  # Use 0 if no F0 detected
    F0_values_per_second.append(mean_f0)

# Display F0 values per second
print(f"F0 values per second ({len(F0_values_per_second)} seconds):", F0_values_per_second)

# Assuming F0_values_per_second already exists from previous steps
# Reuse the existing F0 values and print with corresponding seconds

seconds = list(range(len(F0_values_per_second)))

# Display F0 values per second with corresponding seconds
for sec, f0 in zip(seconds, F0_values_per_second):
    print(f"Second {sec}: F0 = {f0:.2f} Hz")

# Assuming you already have F0_values_per_second and velocities (per second)

# Ensure F0_values_per_second and velocities are already defined in your notebook
# F0_values_per_second = [68.25, 73.83, 72.25, ...]
# velocities = [0.02, -0.01, 0.02, ...]

# Calculate momentum: p = (1 / F0) * v
# To avoid division by zero errors, we check for F0 = 0 and set momentum to 0 in such cases
momentum_per_second = []

for F0, v in zip(F0_values_per_second, velocities):
    if F0 != 0:  # Avoid division by zero
        momentum = (1 / F0) * v
    else:
        momentum = 0
    momentum_per_second.append(momentum)

# Display momentum per second
for sec, momentum in enumerate(momentum_per_second):
    print(f"Second {sec}: Momentum = {momentum:.4f} kg·m/s")

print(velocities)

# Example: Displacements per second (substitute with your actual displacement data)
displacements = [0.5, 0.4, 0.6, 0.8, 0.7]  # Replace with your actual displacement data

# Calculate velocity as the change in displacement over time
velocities = [(displacements[i+1] - displacements[i]) for i in range(len(displacements)-1)]

# Print the calculated velocities
print("Velocities:", velocities)

# Ensure displacements contain 678 values (or however many seconds you have)
if len(displacements) == 678:
    # Calculate velocity for each second (change in displacement over time)
    velocities = [(displacements[i+1] - displacements[i]) for i in range(len(displacements)-1)]

    print(f"Velocities per second ({len(velocities)} values):", velocities)
else:
    print("Error: Displacement data doesn't have 678 values.")

print("Number of displacement values:", len(displacements))

# Recalculate displacements (change in F0 values over time)
displacements = [F0_values_per_second[i+1] - F0_values_per_second[i] for i in range(len(F0_values_per_second) - 1)]

# Ensure the length matches the time intervals (1 per second, so 678 total)
print("Number of recalculated displacements:", len(displacements))

# Calculate velocities as displacement per second (since intervals are 1 second)
velocities = displacements  # because time interval = 1 second

print("Number of velocities:", len(velocities))
print("Sample velocities:", velocities[:10])  # show first 10 for verification

# Display velocities second by second
for i, v in enumerate(velocities, start=1):
    print(f"Second {i}: Velocity = {v}")

# Ensure F0 and velocity data are available
print(f"Number of F0 values: {len(F0_values_per_second)}")
print(f"Number of velocities: {len(velocities)}")

# Check if lengths match for per-second calculations
if len(F0_values_per_second) != len(velocities):
    raise ValueError("Mismatch: F0 values and velocities must have the same length.")

# Calculate momentum: p = v / F0
momentum_per_second = [(v / F0 if F0 != 0 else 0) for F0, v in zip(F0_values_per_second, velocities)]

# Display sample momenta and total count
print(f"Momentum per second (total {len(momentum_per_second)}):")
print(momentum_per_second[:10])  # Show first 10 for verification

# Trim the longer list to match the shorter one
min_length = min(len(F0_values_per_second), len(velocities))

F0_values_per_second = F0_values_per_second[:min_length]
velocities = velocities[:min_length]

# Now calculate momentum
momentum_per_second = [(v / F0 if F0 != 0 else 0) for F0, v in zip(F0_values_per_second, velocities)]

# Display sample momenta and total count
print(f"Momentum per second (total {len(momentum_per_second)}):")
print(momentum_per_second[:10])  # Show first 10 for verification

# Ensure lengths are the same for F0 values and velocities
if len(F0_values_per_second) != len(velocities):
    print(f"Mismatch: F0 values count: {len(F0_values_per_second)}, Velocities count: {len(velocities)}")
    min_length = min(len(F0_values_per_second), len(velocities))
    F0_values_per_second = F0_values_per_second[:min_length]
    velocities = velocities[:min_length]

# Calculate momentum per second
momentum_per_second = []
for F0, v in zip(F0_values_per_second, velocities):
    # To avoid division by zero, check for F0 = 0 and set momentum to 0 in such cases
    if F0 != 0:
        momentum = (v / F0)  # Calculate momentum using F0 as mass proxy
    else:
        momentum = 0  # Handle division by zero scenario
    momentum_per_second.append(momentum)

# Display momentum per second (all values)
print(f"Momentum per second (total {len(momentum_per_second)}):")
print(momentum_per_second)  # Show all momentum values (will be long, consider summarizing)

# Check the length of both lists
print(f"Length of F0 values: {len(F0_values_per_second)}")
print(f"Length of velocities: {len(velocities)}")

# If the lists don't match, trim the longer one
if len(F0_values_per_second) != len(velocities):
    min_length = min(len(F0_values_per_second), len(velocities))
    F0_values_per_second = F0_values_per_second[:min_length]
    velocities = velocities[:min_length]
    print(f"Trimmed both lists to {min_length} elements to match lengths.")

# Calculate momentum per second: p = v / F0
momentum_per_second = []
for F0, v in zip(F0_values_per_second, velocities):
    # Handle division by zero
    if F0 != 0:
        momentum = v / F0
    else:
        momentum = 0  # If F0 is 0, we set momentum to 0
    momentum_per_second.append(momentum)

# Display momentum per second
print(f"Momentum per second (total {len(momentum_per_second)}):")
print(momentum_per_second)  # This will print the full list of momentum values (e.g., 678 values)

# Check the length of both lists
print(f"Length of F0 values: {len(F0_values_per_second)}")
print(f"Length of velocities: {len(velocities)}")

# If the lists don't match, trim the longer one
if len(F0_values_per_second) != len(velocities):
    min_length = min(len(F0_values_per_second), len(velocities))
    F0_values_per_second = F0_values_per_second[:min_length]
    velocities = velocities[:min_length]
    print(f"Trimmed both lists to {min_length} elements to match lengths.")

# Calculate momentum per second: p = v / F0
momentum_per_second = []
for second, (F0, v) in enumerate(zip(F0_values_per_second, velocities), start=1):
    # Handle division by zero
    if F0 != 0:
        momentum = v / F0
    else:
        momentum = 0  # If F0 is 0, we set momentum to 0
    momentum_per_second.append((second, momentum))  # Append second and momentum tuple

# Display momentum per second with time
print(f"Momentum per second (total {len(momentum_per_second)}):")
for second, momentum in momentum_per_second:
    print(f"Second {second}: {momentum}")

# Ensure both F0_values_per_second and velocities have the same length
if len(F0_values_per_second) != len(velocities):
    min_length = min(len(F0_values_per_second), len(velocities))
    F0_values_per_second = F0_values_per_second[:min_length]
    velocities = velocities[:min_length]

# Calculate acceleration for each second: a = (v(t+1) - v(t)) / 1
acceleration_per_second = [0]  # Initialize with 0 for the first second (no previous velocity)
for i in range(1, len(velocities)):
    acceleration = velocities[i] - velocities[i-1]
    acceleration_per_second.append(acceleration)

# Calculate force per second: F = F0 * a
force_per_second = []
for second, (F0, acceleration) in enumerate(zip(F0_values_per_second, acceleration_per_second), start=1):
    force = F0 * acceleration  # Force formula
    force_per_second.append((second, force))

# Display force per second with time
print(f"Force per second (total {len(force_per_second)}):")
for second, force in force_per_second:
    print(f"Second {second}: {force}")

# Ensure both F0_values_per_second and velocities have the same length
if len(F0_values_per_second) != len(velocities):
    min_length = min(len(F0_values_per_second), len(velocities))
    F0_values_per_second = F0_values_per_second[:min_length]
    velocities = velocities[:min_length]

# Calculate acceleration for each second: a = (v(t+1) - v(t)) / 1
acceleration_per_second = [0]  # Initialize with 0 for the first second (no previous velocity)
for i in range(1, len(velocities)):
    acceleration = velocities[i] - velocities[i-1]
    acceleration_per_second.append(acceleration)

# Calculate force per second: F = F0 * a
force_per_second = []
for second, (F0, acceleration) in enumerate(zip(F0_values_per_second, acceleration_per_second), start=1):
    force = F0 * acceleration  # Force formula
    force_per_second.append((second, force))

# Display force per second with time
print(f"Force per second (total {len(force_per_second)}):")
for second, force in force_per_second:
    print(f"Second {second}: Force {force}")

# Assuming force_per_second and velocities are already defined and have the same length (678 values for 678 seconds)

# Calculate work per second: W = F * v
work_per_second = []
for second, (force, velocity) in enumerate(zip(force_per_second, velocities), start=1):
    work = force * velocity  # Work formula
    work_per_second.append((second, work))

# Display work per second with time
print(f"Work per second (total {len(work_per_second)}):")
for second, work in work_per_second:
    print(f"Second {second}: Work {work}")

# Ensure that force_per_second and velocities are lists of floats
force_per_second = [float(force) for force in force_per_second]
velocities = [float(velocity) for velocity in velocities]

# Calculate work per second: W = F * v
work_per_second = []
for second, (force, velocity) in enumerate(zip(force_per_second, velocities), start=1):
    work = force * velocity  # Work formula
    work_per_second.append((second, work))

# Display work per second with time
print(f"Work per second (total {len(work_per_second)}):")
for second, work in work_per_second:
    print(f"Second {second}: Work {work}")

# Extract the force values from force_per_second if they are stored as tuples
force_values = [force for _, force in force_per_second]

# Ensure velocities are lists of floats
velocities = [float(velocity) for velocity in velocities]

# Calculate work per second: W = F * v
work_per_second = []
for second, (force, velocity) in enumerate(zip(force_values, velocities), start=1):
    work = force * velocity  # Work formula
    work_per_second.append((second, work))

# Display work per second with time
print(f"Work per second (total {len(work_per_second)}):")
for second, work in work_per_second:
    print(f"Second {second}: Work {work}")

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Example Data: Time, Position, Velocity, and Acceleration (add your own kinematic data)
time = np.linspace(0, 10, 100)  # Time from 0 to 10 seconds, 100 points
mass = 5  # Mass of the object in kg (example)
position = 0.5 * 2 * time**2  # Example: quadratic position (like free fall)
velocity = np.gradient(position, time)  # Velocity is the derivative of position
acceleration = np.gradient(velocity, time)  # Acceleration is the derivative of velocity

# Function to calculate Force using Newton's Second Law
def calculate_force(acceleration, mass):
    return mass * acceleration

# Calculate Force for each time point
force = calculate_force(acceleration, mass)

# Function to categorize Force Type based on force patterns
def categorize_force(force, velocity, position, time):
    force_type = []

    for i in range(1, len(time)-1):
        # Check the characteristics of the force:

        # Gravity (constant force)
        if np.isclose(force[i], force[0], atol=0.01):  # Constant force
            force_type.append("Gravity")

        # Friction (opposes motion)
        elif force[i] * velocity[i] < 0:  # Force opposes velocity (negative dot product)
            force_type.append("Friction")

        # Tension (positive force acting along a direction)
        elif force[i] > 0 and np.abs(force[i]) > 0.1:  # Positive and larger force
            force_type.append("Tension")

        # Electromagnetic Force (oscillatory or varying with velocity/acceleration)
        elif np.isclose(np.gradient(force[i:i+3]).mean(), 0, atol=0.1):  # Checking for oscillation
            force_type.append("Electromagnetic")

        # Spring Force (proportional to displacement)
        elif np.abs(force[i]) == np.abs(position[i]):  # Force proportional to displacement (Hooke’s Law)
            force_type.append("Spring")

        # Buoyant Force (usually upward force, could be weak in this case)
        elif force[i] > 0 and position[i] > 0.1:  # Positive force related to displacement
            force_type.append("Buoyant")

        # Applied Force (externally applied force)
        elif force[i] > 1 and np.abs(np.gradient(force[i:i+3]).mean()) > 0.1:  # Externally controlled or large force
            force_type.append("Applied")

        # Drag Force (proportional to velocity)
        elif np.abs(force[i]) == np.abs(velocity[i]):  # Force proportional to velocity
            force_type.append("Drag")

        # Normal Force (balances gravity, opposite direction)
        elif np.isclose(force[i], -force[0], atol=0.01):  # Opposite to gravity
            force_type.append("Normal")

        # If none of the above, categorize as "Unknown"
        else:
            force_type.append("Unknown")

    return force_type

# Get Force Type for each second
force_type = categorize_force(force, velocity, position, time)

# Create DataFrame to store results
data = pd.DataFrame({
    'Time (s)': time[1:-1],
    'Force (N)': force[1:-1],
    'Force Type': force_type
})

# Display the results
print(data.head())

# Plot the force type vs. time to visualize the force type changes
plt.plot(data['Time (s)'], [1 if x == 'Gravity' else 2 if x == 'Friction' else 3 if x == 'Tension' else 4 if x == 'Electromagnetic' else 5 if x == 'Spring' else 6 if x == 'Buoyant' else 7 if x == 'Applied' else 8 if x == 'Drag' else 9 for x in data['Force Type']])
plt.title('Force Type over Time')
plt.xlabel('Time (s)')
plt.ylabel('Force Type')
plt.yticks([1, 2, 3, 4, 5, 6, 7, 8, 9], ['Gravity', 'Friction', 'Tension', 'Electromagnetic', 'Spring', 'Buoyant', 'Applied', 'Drag', 'Normal'])
plt.grid(True)
plt.show()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import wavfile

# Function to read the audio file and get the data
def read_audio(file_path):
    sample_rate, audio_data = wavfile.read(file_path)  # Read the audio file
    return sample_rate, audio_data

# Function to calculate velocity and acceleration from position (audio data)
def calculate_velocity_and_acceleration(audio_data, sample_rate):
    time = np.arange(0, len(audio_data)) / sample_rate  # Convert the sample points to time
    velocity = np.gradient(audio_data, time)  # Calculate velocity
    acceleration = np.gradient(velocity, time)  # Calculate acceleration
    return velocity, acceleration, time

# Function to calculate Force (F = m * a)
def calculate_force(acceleration, mass):
    return mass * acceleration

# Function to categorize force type based on patterns
def categorize_force(force, velocity, position, time):
    force_type = []

    for i in range(1, len(time)-1):
        # Check the characteristics of the force:

        # Gravity (constant force)
        if np.isclose(force[i], force[0], atol=0.01):  # Constant force
            force_type.append("Gravity")

        # Friction (opposes motion)
        elif force[i] * velocity[i] < 0:  # Force opposes velocity (negative dot product)
            force_type.append("Friction")

        # Tension (positive force acting along a direction)
        elif force[i] > 0 and np.abs(force[i]) > 0.1:  # Positive and larger force
            force_type.append("Tension")

        # Electromagnetic Force (oscillatory or varying with velocity/acceleration)
        elif np.isclose(np.gradient(force[i:i+3]).mean(), 0, atol=0.1):  # Checking for oscillation
            force_type.append("Electromagnetic")

        # Spring Force (proportional to displacement)
        elif np.abs(force[i]) == np.abs(position[i]):  # Force proportional to displacement (Hooke’s Law)
            force_type.append("Spring")

        # Buoyant Force (usually upward force, could be weak in this case)
        elif force[i] > 0 and position[i] > 0.1:  # Positive force related to displacement
            force_type.append("Buoyant")

        # Applied Force (externally applied force)
        elif force[i] > 1 and np.abs(np.gradient(force[i:i+3]).mean()) > 0.1:  # Externally controlled or large force
            force_type.append("Applied")

        # Drag Force (proportional to velocity)
        elif np.abs(force[i]) == np.abs(velocity[i]):  # Force proportional to velocity
            force_type.append("Drag")

        # Normal Force (balances gravity, opposite direction)
        elif np.isclose(force[i], -force[0], atol=0.01):  # Opposite to gravity
            force_type.append("Normal")

        # If none of the above, categorize as "Unknown"
        else:
            force_type.append("Unknown")

    return force_type

# Main function to process the entire audio file and calculate the force type every second
def analyze_audio_forces(file_path, mass):
    sample_rate, audio_data = read_audio(file_path)  # Read the audio file

    # Calculate velocity and acceleration
    velocity, acceleration, time = calculate_velocity_and_acceleration(audio_data, sample_rate)

    # Calculate force for each second (mass * acceleration)
    force = calculate_force(acceleration, mass)

    # Categorize force types
    force_type = categorize_force(force, velocity, audio_data, time)

    # Create DataFrame to store results
    data = pd.DataFrame({
        'Time (s)': time[1:-1],  # Remove the first and last time points to match the force_type length
        'Force (N)': force[1:-1],
        'Force Type': force_type
    })

    return data

# Set mass of vocal cords (example mass in kg)
mass = 5  # Modify this based on your object/vocal cords mass

# Path to your audio file
file_path = 'path_to_your_audio_file.wav'

# Analyze forces in the audio data
data = analyze_audio_forces(file_path, mass)

# Display the first few rows of the DataFrame
print(data.head())

# Plot the force type vs. time to visualize the force type changes
plt.figure(figsize=(10, 6))
plt.plot(data['Time (s)'], [1 if x == 'Gravity' else 2 if x == 'Friction' else 3 if x == 'Tension' else 4 if x == 'Electromagnetic' else 5 if x == 'Spring' else 6 if x == 'Buoyant' else 7 if x == 'Applied' else 8 if x == 'Drag' else 9 for x in data['Force Type']])
plt.title('Force Type over Time (Audio Analysis)')
plt.xlabel('Time (s)')
plt.ylabel('Force Type')
plt.yticks([1, 2, 3, 4, 5, 6, 7, 8, 9], ['Gravity', 'Friction', 'Tension', 'Electromagnetic', 'Spring', 'Buoyant', 'Applied', 'Drag', 'Normal'])
plt.grid(True)
plt.show()

from google.colab import drive
drive.mount('/content/drive')

file_path = '/content/drive/MyDrive/Research/AudioFiles/sample_audio.wav'

# Step 1: Set the correct file path
file_path = '/content/drive/MyDrive/Research/AudioFiles/sample_audio.wav'  # Update this with the actual path

# Step 2: Analyze the audio
data = analyze_audio_forces(file_path, mass)

# Step 3: Display the first few rows of the DataFrame
print(data.head())

# Step 4: Plot the force type over time
plt.figure(figsize=(10, 6))
plt.plot(data['Time (s)'], [1 if x == 'Gravity' else 2 if x == 'Friction' else 3 if x == 'Tension' else 4 if x

# Step 1: Set the correct file path
file_path = '/content/drive/MyDrive/Research/AudioFiles/sample_audio.wav'  # Update this with the actual path

# Step 2: Analyze the audio
data = analyze_audio_forces(file_path, mass)

# Step 3: Display the first few rows of the DataFrame
print(data.head())

# Step 4: Plot the force type over time
plt.figure(figsize=(10, 6))

# Convert force types to numerical values for plotting
force_type_map = {
    'Gravity': 1,
    'Friction': 2,
    'Tension': 3,
    'Electromagnetic': 4,
    'Spring': 5,
    'Buoyant': 6,
    'Applied': 7,
    'Drag': 8,
    'Normal': 9
}

# Map the force types to corresponding numbers
force_numerical = data['Force Type'].map(force_type_map)

# Plot the force type over time
plt.plot(data['Time (s)'], force_numerical)

# Set plot labels and title
plt.title('Force Type over Time (Audio Analysis)')
plt.xlabel('Time (s)')
plt.ylabel('Force Type')
plt.yticks([1, 2, 3, 4, 5, 6, 7, 8, 9], ['Gravity', 'Friction', 'Tension', 'Electromagnetic', 'Spring', 'Buoyant', 'Applied', 'Drag', 'Normal'])
plt.grid(True)
plt.show()

!ls '/content/drive/MyDrive/Research/AudioFiles'

!ls '/content/drive/MyDrive/Research/AudioFiles'

!ls '/content/drive/MyDrive/AudioFiles'

file_path = '/content/drive/MyDrive/CorrectFolder/your_audio_file.wav'

# Step 1: Set the correct file path
file_path = '/content/drive/MyDrive/Research/AudioFiles/your_audio_file.wav'  # Update this with the actual path

# Step 2: Analyze the audio
data = analyze_audio_forces(file_path, mass)

# Step 3: Display the first few rows of the DataFrame
print(data.head())

# Step 4: Plot the force type over time
plt.figure(figsize=(10, 6))

# Convert force types to numerical values for plotting
force_type_map = {
    'Gravity': 1,
    'Friction': 2,
    'Tension': 3,
    'Electromagnetic': 4,
    'Spring': 5,
    'Buoyant': 6,
    'Applied': 7,
    'Drag': 8,
    'Normal': 9
}

# Map the force types to corresponding numbers
force_numerical = data['Force Type'].map(force_type_map)

# Plot the force type over time
plt.plot(data['Time (s)'], force_numerical)

# Set plot labels and title
plt.title('Force Type over Time (Audio Analysis)')
plt.xlabel('Time (s)')
plt.ylabel('Force Type')
plt.yticks([1, 2, 3, 4, 5, 6, 7, 8, 9], ['Gravity', 'Friction', 'Tension', 'Electromagnetic', 'Spring', 'Buoyant', 'Applied', 'Drag', 'Normal'])
plt.grid(True)
plt.show()

import pandas as pd

# Define the function to deduce force type based on kinematics
def deduce_force_type(acceleration, velocity, displacement):
    if acceleration > 9.8:  # Gravity or a large restoring force (e.g., spring)
        return 'Gravity'
    elif velocity < 0 and acceleration > 0:  # Slowing down due to friction
        return 'Friction'
    elif velocity == 0 and displacement > 0:  # Restoring force (tension/spring)
        return 'Tension'
    elif acceleration == 0:  # No acceleration; might be a normal force or static
        return 'Normal'
    # Add more rules based on other forces (electromagnetic, buoyant, etc.)
    return 'Unknown'  # Default case

# Step 1: Analyze the audio (this part would include your kinematic calculations)
data = analyze_audio_forces(file_path, mass)

# Step 2: Apply the deduction logic to each time point
force_types = []
for index, row in data.iterrows():
    acceleration = row['acceleration']  # Example kinematic value
    velocity = row['velocity']          # Example kinematic value
    displacement = row['displacement']  # Example kinematic value
    force_type = deduce_force_type(acceleration, velocity, displacement)
    force_types.append(force_type)

# Add the force types to the DataFrame
data['Force Type'] = force_types

# Step 3: Display the updated DataFrame with deduced force types
print(data.head())

# Step 4: Plot the force type over time (as previously described)
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))

# Convert force types to numerical values for plotting
force_type_map = {
    'Gravity': 1,
    'Friction': 2,
    'Tension': 3,
    'Electromagnetic': 4,
    'Spring': 5,
    'Buoyant': 6,
    'Applied': 7,
    'Drag': 8,
    'Normal': 9
}

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile

# Set the correct file path for your audio file on Google Drive
file_path = '/content/drive/MyDrive/Research/AudioFiles/sample.wav'

# Define a function to read audio data and analyze forces (simplified version)
def analyze_audio_forces(file_path, mass):
    # Read the audio file (WAV format)
    sample_rate, data = wavfile.read(file_path)

    # Assuming the data is stereo (2 channels), convert to mono by averaging
    if len(data.shape) == 2:
        data = data.mean(axis=1)

    # Create a time vector based on the sample rate and audio length
    time = np.arange(0, len(data)) / sample_rate

    # Calculate kinematic values like velocity and acceleration
    # Here we're just using basic differences; you can expand this as needed
    velocity = np.diff(data) * sample_rate
    acceleration = np.diff(velocity) * sample_rate

    # Assume mass proxy and use it for force calculation
    force = mass * acceleration  # Simple F = ma (assuming mass proxy already calculated)

    # Create a DataFrame for further analysis
    df = pd.DataFrame({
        'Time (s)': time[1:],  # Time vector for velocity and acceleration (after diff)
        'Acceleration': acceleration,
        'Velocity': velocity,
        'Force (N)': force
    })

    return df

# Example mass value (you can replace this with your calculated mass proxy)
mass = 1.0  # Replace this with the actual mass proxy calculation

# Step 1: Analyze the audio and get kinematic data
data = analyze_audio_forces(file_path, mass)

# Define a function to deduce the force type based on kinematics
def deduce_force_type(acceleration, velocity, displacement):
    if acceleration > 9.8:  # Gravity or large restoring force (e.g., spring)
        return 'Gravity'
    elif velocity < 0 and acceleration > 0:  # Slowing down due to friction
        return 'Friction'
    elif velocity == 0 and displacement > 0:  # Restoring force (tension/spring)
        return 'Tension'
    elif acceleration == 0:  # No acceleration; might be a normal force or static
        return 'Normal'
    # Add more rules based on other forces (electromagnetic, buoyant, etc.)
    return 'Unknown'  # Default case

# Step 2: Apply the deduction logic to each time point
force_types = []
for index, row in data.iterrows():
    acceleration = row['Acceleration']  # Example kinematic value
    velocity = row['Velocity']          # Example kinematic value
    displacement = row['Force (N)']     # Example kinematic value (can also use other factors)
    force_type = deduce_force_type(acceleration, velocity, displacement)
    force_types.append(force_type)

# Add the force types to the DataFrame
data['Force Type'] = force_types

# Step 3: Display the updated DataFrame with deduced force types
print(data.head())

# Step 4: Plot the force type over time (as previously described)
plt.figure(figsize=(10, 6))

# Convert force types to numerical values for plotting
force_type_map = {
    'Gravity': 1,
    'Friction': 2,
    'Tension': 3,
    'Electromagnetic': 4,
    'Spring': 5,
    'Buoyant': 6,
    'Applied': 7,
    'Drag': 8,
    'Normal': 9
}

force_numerical = data['Force Type'].map(force_type_map)
plt.plot(data['Time (s)'], force_numerical)

# Set plot labels and title
plt.title('Force Type over Time (Audio Analysis)')
plt.xlabel('Time (s)')
plt.ylabel('Force Type')
plt.yticks([1, 2, 3, 4, 5, 6, 7, 8, 9], ['Gravity', 'Friction', 'Tension', 'Electromagnetic', 'Spring', 'Buoyant', 'Applied', 'Drag', 'Normal'])
plt.grid(True)
plt.show()

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Assuming 'data' is the DataFrame with your kinematic values (already calculated)
# Example kinematic data (replace this with your actual data)
data = pd.DataFrame({
    'Time (s)': np.arange(0, 678),  # Example time vector for 678 seconds
    'Acceleration': np.random.normal(0, 1, 678),  # Example acceleration values
    'Velocity': np.random.normal(0, 1, 678),  # Example velocity values
    'Displacement': np.random.normal(0, 1, 678),  # Example displacement values
})

# Define a function to deduce the force type based on kinematics
def deduce_force_type(acceleration, velocity, displacement):
    if acceleration > 9.8:  # Gravity or large restoring force (e.g., spring)
        return 'Gravity'
    elif velocity < 0 and acceleration > 0:  # Slowing down due to friction
        return 'Friction'
    elif velocity == 0 and displacement > 0:  # Restoring force (tension/spring)
        return 'Tension'
    elif acceleration == 0 and velocity == 0:  # No movement (Normal or static)
        return 'Normal'
    elif displacement > 0 and velocity < 0:  # Objects at rest or moving against restoring force
        return 'Spring'
    elif velocity == 0 and acceleration == 0:  # Forces at rest or under constant velocity
        return 'Applied'
    elif acceleration < 0 and velocity > 0:  # Forces slowing down the motion (Drag)
        return 'Drag'
    elif displacement < 0 and velocity > 0:  # Forces exerted due to buoyant effects (e.g., upward forces)
        return 'Buoyant'
    elif velocity > 0 and acceleration == 0:  # Electromagnetic forces when velocity is constant
        return 'Electromagnetic'
    # Default case for unknown forces
    return 'Unknown'

# Apply the deduction logic to each time point in the existing data
force_types = []
for index, row in data.iterrows():
    acceleration = row['Acceleration']
    velocity = row['Velocity']
    displacement = row['Displacement']
    force_type = deduce_force_type(acceleration, velocity, displacement)
    force_types.append(force_type)

# Add the force types to the DataFrame
data['Force Type'] = force_types

# Display the updated DataFrame with deduced force types
print(data.head())

# Plot the force type over time
plt.figure(figsize=(10, 6))

# Convert force types to numerical values for plotting
force_type_map = {
    'Gravity': 1,
    'Friction': 2,
    'Tension': 3,
    'Electromagnetic': 4,
    'Spring': 5,
    'Buoyant': 6,
    'Applied': 7,
    'Drag': 8,
    'Normal': 9
}

force_numerical = data['Force Type'].map(force_type_map)
plt.plot(data['Time (s)'], force_numerical)

# Set plot labels and title
plt.title('Force Type over Time (Kinematic Data Analysis)')
plt.xlabel('Time (s)')
plt.ylabel('Force Type')
plt.yticks([1, 2, 3, 4, 5, 6, 7, 8, 9], ['Gravity', 'Friction', 'Tension', 'Electromagnetic', 'Spring', 'Buoyant', 'Applied', 'Drag', 'Normal'])
plt.grid(True)
plt.show()

import pandas as pd
import numpy as np

# Example kinematic data (replace this with your actual data)
data = pd.DataFrame({
    'Time (s)': np.arange(0, 678),  # Time for 678 seconds
    'Acceleration': np.random.normal(0, 1, 678),  # Example acceleration values
    'Velocity': np.random.normal(0, 1, 678),  # Example velocity values
    'Displacement': np.random.normal(0, 1, 678),  # Example displacement values
})

# Define a function to deduce the force type based on kinematics
def deduce_force_type(acceleration, velocity, displacement):
    if acceleration > 9.8:  # Gravity or large restoring force (e.g., spring)
        return 'Gravity'
    elif velocity < 0 and acceleration > 0:  # Slowing down due to friction
        return 'Friction'
    elif velocity == 0 and displacement > 0:  # Restoring force (tension/spring)
        return 'Tension'
    elif acceleration == 0 and velocity == 0:  # No movement (Normal or static)
        return 'Normal'
    elif displacement > 0 and velocity < 0:  # Objects at rest or moving against restoring force
        return 'Spring'
    elif velocity == 0 and acceleration == 0:  # Forces at rest or under constant velocity
        return 'Applied'
    elif acceleration < 0 and velocity > 0:  # Forces slowing down the motion (Drag)
        return 'Drag'
    elif displacement < 0 and velocity > 0:  # Forces exerted due to buoyant effects (e.g., upward forces)
        return 'Buoyant'
    elif velocity > 0 and acceleration == 0:  # Electromagnetic forces when velocity is constant
        return 'Electromagnetic'
    # Default case for unknown forces
    return 'Unknown'

# Apply the deduction logic to each time point in the existing data
force_info = []
for index, row in data.iterrows():
    time = row['Time (s)']
    acceleration = row['Acceleration']
    velocity = row['Velocity']
    displacement = row['Displacement']

    # Deduce the type of force and calculate its magnitude (proxy, using acceleration for simplicity)
    force_type = deduce_force_type(acceleration, velocity, displacement)

    # You can calculate magnitude here (using acceleration as a proxy for force magnitude)
    force_magnitude = abs(acceleration)  # Example: magnitude is the absolute value of acceleration for simplicity

    # Append the results
    force_info.append({'Time (s)': time, 'Force Type': force_type, 'Force Magnitude (N)': force_magnitude})

# Convert the force information into a DataFrame
force_df = pd.DataFrame(force_info)

# Display the force types and magnitudes
for index, row in force_df.iterrows():
    print(f"Time: {row['Time (s)']} s - Force Type: {row['Force Type']} - Magnitude: {row['Force Magnitude (N)']} N")

# Assuming 'data' contains the force magnitudes and their corresponding types

# Function to check equilibrium state
def check_equilibrium(net_force, tolerance=1e-5):
    return abs(net_force) < tolerance  # Consider small tolerances for zero force

# Add the equilibrium state to the data
data['Equilibrium'] = data['Force (N)'].apply(lambda x: 'Equilibrium' if check_equilibrium(x) else 'Not in Equilibrium')

# Display the results
for index, row in data.iterrows():
    print(f"Time: {row['Time (s)']}s, Force: {row['Force (N)']}N, Type: {row['Force Type']}, Equilibrium: {row['Equilibrium']}")

# Check the column names in the dataset
print(data.columns)

# Function to check equilibrium state
def check_equilibrium(net_force, tolerance=1e-5):
    return abs(net_force) < tolerance  # Consider small tolerances for zero force

# Add the equilibrium state to the data (use the correct column name)
data['Equilibrium'] = data['Force'].apply(lambda x: 'Equilibrium' if check_equilibrium(x) else 'Not in Equilibrium')

# Display the results
for index, row in data.iterrows():
    print(f"Time: {row['Time (s)']}s, Force: {row['Force']}N, Type: {row['Force Type']}, Equilibrium: {row['Equilibrium']}")

# Check the column names in your DataFrame
print(data.columns)

# Add Force calculation (using the mass proxy and acceleration)
data['Force (N)'] = data['Acceleration'] * mass  # mass is the mass proxy you have

# Function to check equilibrium state
def check_equilibrium(net_force, tolerance=1e-5):
    return abs(net_force) < tolerance  # Consider small tolerances for zero force

# Add the equilibrium state to the data
data['Equilibrium'] = data['Force (N)'].apply(lambda x: 'Equilibrium' if check_equilibrium(x) else 'Not in Equilibrium')

# Display the results
for index, row in data.iterrows():
    print(f"Time: {row['Time (s)']}s, Force: {row['Force (N)']}N, Type: {row['Force Type']}, Equilibrium: {row['Equilibrium']}")

# Add Force calculation (using the mass proxy and acceleration)
data['Force (N)'] = data['Acceleration'] * mass  # mass is the mass proxy you have

# Add Force Type based on predefined conditions (patterns)
def get_force_type(force):
    # Define your patterns here for each force type (example thresholds)
    if force < 0.1:
        return 'Gravity'
    elif force < 0.5:
        return 'Friction'
    elif force < 1.0:
        return 'Tension'
    elif force < 2.0:
        return 'Spring'
    elif force < 3.0:
        return 'Applied'
    elif force < 5.0:
        return 'Normal'
    elif force < 7.0:
        return 'Drag'
    elif force < 10.0:
        return 'Electromagnetic'
    else:
        return 'Buoyant'

# Add the 'Force Type' column
data['Force Type'] = data['Force (N)'].apply(get_force_type)

# Function to check equilibrium state
def check_equilibrium(net_force, tolerance=1e-5):
    return abs(net_force) < tolerance  # Consider small tolerances for zero force

# Add the equilibrium state to the data
data['Equilibrium'] = data['Force (N)'].apply(lambda x: 'Equilibrium' if check_equilibrium(x) else 'Not in Equilibrium')

# Display the results
for index, row in data.iterrows():
    print(f"Time: {row['Time (s)']}s, Force: {row['Force (N)']}N, Type: {row['Force Type']}, Equilibrium: {row['Equilibrium']}")

import pandas as pd
import numpy as np

# Assuming you have 678 kinematic data points for the 678 seconds of the audio.

# Example: You should have actual kinematic values for displacement, velocity, and acceleration here
time_intervals = np.linspace(0, 677, 678)  # 678 intervals for 678 seconds, ranging from 0 to 677

# Replace these with your actual kinematic data
displacement = np.random.rand(678)  # Replace with your displacement values
velocity = np.random.rand(678)  # Replace with your velocity values
acceleration = np.random.rand(678)  # Replace with your acceleration values
angle = np.random.rand(678) * 180  # Replace with your angle values (0 to 180 degrees)
radius = np.ones(678)  # Replace with your radius values (or keep as 1 for simplicity)

# Create DataFrame from your data
data = pd.DataFrame({
    'Time (s)': time_intervals,
    'Displacement': displacement,
    'Velocity': velocity,
    'Acceleration': acceleration,
    'Angle': angle,
    'Radius': radius
})

# Motion detection function
def detect_motion_type(row):
    """
    Function to detect the motion type based on the kinematic data for each second.
    """
    velocity = row['Velocity']
    acceleration = row['Acceleration']
    displacement = row['Displacement']
    angle = row['Angle']
    radius = row['Radius']

    # Detecting motion type based on velocity, acceleration, displacement, and angle
    if velocity == 0 and acceleration == 0:
        return "Rest"  # No motion
    elif acceleration == 0 and velocity != 0:
        return "Linear or Translational Motion"  # Constant velocity (linear motion)
    elif acceleration != 0 and velocity != 0:
        if angle != 0 and radius != 0:
            return "Circular Motion"  # Circular motion based on angle and radius
        else:
            return "Rotational Motion"  # Rotational motion, acceleration is not zero
    elif displacement != 0 and velocity == 0:
        return "Oscillatory Motion"  # Oscillating, with zero velocity at certain points (e.g., at peak)
    elif acceleration != 0 and angle != 0:
        if radius != 0:
            return "Rotational Motion"  # Rotational motion based on angle and radius
        else:
            return "Projectile Motion"  # Projectile motion, when there is an angle and velocity
    elif acceleration == 0 and displacement != 0:
        return "Random Motion"  # If there is no specific pattern in motion (e.g., random walk)
    else:
        return "Unknown Motion"  # If no condition matches

# Apply the function to the data to get the motion type at each time point
data['Motion Type'] = data.apply(detect_motion_type, axis=1)

# Now, print or store the results for every second
# Print each second and its corresponding motion type
for index, row in data.iterrows():
    print(f"Second {row['Time (s)']:.1f}: {row['Motion Type']}")

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text to display
    text = (
        f"Second {second}:\n"
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create a text clip for the current second
    text_clip = TextClip(
        text,
        fontsize=20,
        color="white",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("center").set_duration(1).set_start(second)

    text_clips.append(text_clip)

# Load the audio file as an AudioFileClip
audio_clip = AudioFileClip(audio_file)

# Combine the text clips into a single video clip
video_clip = CompositeVideoClip(text_clips).set_audio(audio_clip)

# Export the video to a file
output_file = "/content/drive/My Drive/output.mp4"  # Save the output video to Google Drive
video_clip.write_videofile(output_file, fps=1)  # 1 frame per second

# Display the video in Colab
from IPython.display import Video
Video(output_file)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text to display
    text = (
        f"Second {second}:\n"
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create a text clip for the current second
    text_clip = TextClip(
        text,
        fontsize=20,
        color="white",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("center").set_duration(1).set_start(second)

    text_clips.append(text_clip)

# Load the audio file as an AudioFileClip
audio_clip = AudioFileClip(audio_file)

# Combine the text clips into a single video clip
video_clip = CompositeVideoClip(text_clips).set_audio(audio_clip)

# Export the video to a file
output_file = "/content/drive/My Drive/output.mp4"  # Save the output video to Google Drive
video_clip.write_videofile(output_file, fps=1)  # 1 frame per second

# Display the video in Colab
from IPython.display import Video
Video(output_file)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Install ffmpeg
!apt install ffmpeg

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text to display
    text = (
        f"Second {second}:\n"
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create a text clip for the current second
    text_clip = TextClip(
        text,
        fontsize=20,
        color="white",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("center").set_duration(1).set_start(second)

    text_clips.append(text_clip)

# Load the audio file as an AudioFileClip
audio_clip = AudioFileClip(audio_file)

# Combine the text clips into a single video clip
video_clip = CompositeVideoClip(text_clips).set_audio(audio_clip)

# Export the video to a file
output_file = "/content/drive/My Drive/output.mp4"  # Save the output video to Google Drive
video_clip.write_videofile(output_file, fps=1)  # 1 frame per second

# Display the video in Colab
from IPython.display import Video
Video(output_file)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Install ffmpeg
!apt install ffmpeg

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text to display
    text = (
        f"Second {second}:\n"
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create a text clip for the current second
    text_clip = TextClip(
        text,
        fontsize=20,
        color="white",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("center").set_duration(1).set_start(second)

    text_clips.append(text_clip)

# Load the audio file as an AudioFileClip
audio_clip = AudioFileClip(audio_file)

# Combine the text clips into a single video clip
video_clip = CompositeVideoClip(text_clips).set_audio(audio_clip)

# Export the video to a file
output_file = "/content/drive/My Drive/output.mp4"  # Save the output video to Google Drive
video_clip.write_videofile(output_file, fps=1)  # 1 frame per second

# Display the video in Colab
from IPython.display import Video
Video(output_file)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Install ffmpeg
!apt install ffmpeg

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text to display
    text = (
        f"Second {second}:\n"
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create a text clip for the current second
    text_clip = TextClip(
        text,
        fontsize=20,
        color="white",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("center").set_duration(1).set_start(second)

    text_clips.append(text_clip)

# Load the audio file as an AudioFileClip
audio_clip = AudioFileClip(audio_file)

# Combine the text clips into a single video clip
video_clip = CompositeVideoClip(text_clips).set_audio(audio_clip)

# Export the video to a file
output_file = "/content/drive/My Drive/output.mp4"  # Save the output video to Google Drive
video_clip.write_videofile(output_file, fps=1)  # 1 frame per second

# Display the video in Colab
from IPython.display import Video
Video(output_file)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Install ffmpeg
!apt install ffmpeg

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text to display
    text = (
        f"Second {second}:\n"
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create a text clip for the current second
    text_clip = TextClip(
        text,
        fontsize=20,
        color="white",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("center").set_duration(1).set_start(second)

    text_clips.append(text_clip)

# Load the audio file as an AudioFileClip
audio_clip = AudioFileClip(audio_file)

# Combine the text clips into a single video clip
video_clip = CompositeVideoClip(text_clips).set_audio(audio_clip)

# Export the video to a file
output_file = "/content/drive/My Drive/output.mp4"  # Save the output video to Google Drive
video_clip.write_videofile(output_file, fps=1)  # 1 frame per second

# Display the video in Colab
from IPython.display import Video
Video(output_file)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Install ffmpeg
!apt install ffmpeg

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Example: Replace these with your actual calculated force and motion values
force_magnitude = np.random.rand(duration)  # Replace with your force magnitude values
force_type = ["Gravity", "Friction", "Tension", "Normal"][np.random.randint(0, 4, duration)]  # Replace with your force types
motion_type = ["Linear", "Circular", "Rotational", "Oscillatory"][np.random.randint(0, 4, duration)]  # Replace with your motion types

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text for the left column (values)
    left_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create the text for the right column (force and motion)
    right_text = (
        f"Force: {force_magnitude[second]:.4f} N\n"
        f"Type: {force_type[second]}\n"
        f"Motion: {motion_type[second]}"
    )

    # Create a text clip for the time (top center)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=30,
        color="yellow",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("top").set_duration(1).set_start(second)

    # Create a text clip for the left column (values)
    left_clip = TextClip(
        left_text,
        fontsize=20,
        color="yellow",
        bg_color="black",
        size=(320, 480),  # Adjust size as needed
    ).set_position("left").set_duration(1).set_start(second)

    # Create a text clip for the right column (force and motion)
    right_clip = TextClip(
        right_text,
        fontsize=30,  # Larger font size for force and motion
        color="yellow",
        bg_color="black",
        size=(320, 480),  # Adjust size as needed
    ).set_position("right").set_duration(1).set_start(second)

    # Combine all clips into a single frame
    frame_clip = CompositeVideoClip([time_clip, left_clip, right_clip])
    text_clips.append(frame_clip)

# Load the audio file as an AudioFileClip
audio_clip = AudioFileClip(audio_file)

# Combine the text clips into a single video clip
video_clip = CompositeVideoClip(text_clips).set_audio(audio_clip)

# Export the video to a file
output_file = "/content/drive/My Drive/output.mp4"  # Save the output video to Google Drive
video_clip.write_videofile(output_file, fps=1)  # 1 frame per second

# Display the video in Colab
from IPython.display import Video
Video(output_file)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Install ffmpeg
!apt install ffmpeg

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Example: Replace these with your actual calculated force and motion values
force_magnitude = np.random.rand(duration)  # Replace with your force magnitude values
force_type = ["Gravity", "Friction", "Tension", "Normal"]
motion_type = ["Linear", "Circular", "Rotational", "Oscillatory"]

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Randomly select force type and motion type for the current second
    force_idx = np.random.randint(0, 4)  # Random index for force type
    motion_idx = np.random.randint(0, 4)  # Random index for motion type

    # Create the text for the left column (values)
    left_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create the text for the right column (force and motion)
    right_text = (
        f"Force: {force_magnitude[second]:.4f} N\n"
        f"Type: {force_type[force_idx]}\n"
        f"Motion: {motion_type[motion_idx]}"
    )

    # Create a text clip for the time (top center)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=30,
        color="yellow",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("top").set_duration(1).set_start(second)

    # Create a text clip for the left column (values)
    left_clip = TextClip(
        left_text,
        fontsize=20,
        color="yellow",
        bg_color="black",
        size=(320, 480),  # Adjust size as needed
    ).set_position("left").set_duration(1).set_start(second)

    # Create a text clip for the right column (force and motion)
    right_clip = TextClip(
        right_text,
        fontsize=30,  # Larger font size for force and motion
        color="yellow",
        bg_color="black",
        size=(320, 480),  # Adjust size as needed
    ).set_position("right").set_duration(1).set_start(second)

    # Combine all clips into a single frame
    frame_clip = CompositeVideoClip([time_clip, left_clip, right_clip])
    text_clips.append(frame_clip)

# Load the audio file as an AudioFileClip
audio_clip = AudioFileClip(audio_file)

# Combine the text clips into a single video clip
video_clip = CompositeVideoClip(text_clips).set_audio(audio_clip)

# Export the video to a file
output_file = "/content/drive/My Drive/output.mp4"  # Save the output video to Google Drive
video_clip.write_videofile(output_file, fps=1)  # 1 frame per second

# Display the video in Colab
from IPython.display import Video
Video(output_file)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Install ffmpeg
!apt install ffmpeg

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Define all 9 forces and 6 motions
forces = [
    "Gravitational Force", "Electromagnetic Force", "Strong Nuclear Force",
    "Weak Nuclear Force", "Frictional Force", "Tension Force",
    "Normal Force", "Applied Force", "Spring Force"
]
motions = [
    "Linear Motion", "Circular Motion", "Rotational Motion",
    "Oscillatory Motion", "Projectile Motion", "Random Motion"
]

# Example: Replace these with your actual calculated force and motion values
force_magnitude = np.random.rand(duration)  # Replace with your force magnitude values
force_type = [forces[np.random.randint(0, 9)] for _ in range(duration)]  # Random force types
motion_type = [motions[np.random.randint(0, 6)] for _ in range(duration)]  # Random motion types

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text for the left column (kinematics elements)
    left_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create the text for the right column (force and motion)
    right_text = (
        f"Force: {force_magnitude[second]:.4f} N\n"
        f"Type: {force_type[second]}\n"
        f"Motion: {motion_type[second]}"
    )

    # Create a text clip for the time (top center)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=30,
        color="yellow",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("top").set_duration(1).set_start(second)

# Create a text clip for the left column (kinematics elements)
left_clip = TextClip(
    left_text,
    fontsize=20,
    color="yellow",
    bg_color="black",
    size=(320, 480),  # Adjust size as needed
).set_position("left").set_duration(1)

import numpy as np
from pydub import AudioSegment
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive

# Install ImageMagick and configure policy
!apt install imagemagick
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Install ffmpeg
!apt install ffmpeg

# Mount Google Drive (if not already mounted)
drive.mount('/content/drive')

# Path to the audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Update with the correct file name and path

# Load the audio file
try:
    audio = AudioSegment.from_file(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    raise

# Duration in seconds (pydub uses milliseconds)
duration = len(audio) // 1000

# Example: Replace these with your actual calculated values
distance = np.random.rand(duration)  # Replace with your distance values
displacement = np.random.rand(duration)  # Replace with your displacement values
speed = np.random.rand(duration)  # Replace with your speed values
velocity = np.random.rand(duration)  # Replace with your velocity values
acceleration = np.random.rand(duration)  # Replace with your acceleration values
momentum = np.random.rand(duration)  # Replace with your momentum values
potential_energy = np.random.rand(duration)  # Replace with your potential energy values
kinetic_energy = np.random.rand(duration)  # Replace with your kinetic energy values
inertia = np.random.rand(duration)  # Replace with your inertia values
impulse = np.random.rand(duration)  # Replace with your impulse values

# Define all 9 forces and 6 motions
forces = [
    "Gravitational Force", "Electromagnetic Force", "Strong Nuclear Force",
    "Weak Nuclear Force", "Frictional Force", "Tension Force",
    "Normal Force", "Applied Force", "Spring Force"
]
motions = [
    "Linear Motion", "Circular Motion", "Rotational Motion",
    "Oscillatory Motion", "Projectile Motion", "Random Motion"
]

# Example: Replace these with your actual calculated force and motion values
force_magnitude = np.random.rand(duration)  # Replace with your force magnitude values
force_type = [forces[np.random.randint(0, 9)] for _ in range(duration)]  # Random force types
motion_type = [motions[np.random.randint(0, 6)] for _ in range(duration)]  # Random motion types

# Create a list of text clips for each second
text_clips = []
for second in range(duration):
    # Create the text for the left column (kinematics elements)
    left_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    # Create the text for the right column (force and motion)
    right_text = (
        f"Force: {force_magnitude[second]:.4f} N\n"
        f"Type: {force_type[second]}\n"
        f"Motion: {motion_type[second]}"
    )

    # Create a text clip for the time (top center)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=30,
        color="yellow",
        bg_color="black",
        size=(640, 50),  # Adjust size as needed
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Create a text clip for the left column (kinematics elements)
    left_clip = TextClip(
        left_text,
        fontsize=20,
        color="yellow",
        bg_color="black",
        size=(320, 480),  # Adjust size as needed
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Create a text clip for the right column (force and motion)
    right_clip = TextClip(
        right_text,
        fontsize=24,  # Slightly larger font for emphasis
        color="yellow",
        bg_color="black",
        size=(320, 480),  # Adjust size as needed
    ).set_position(("right", "center")).set_duration(1).set_start(second)

    # Combine all clips for this second
    composite_clip = CompositeVideoClip([time_clip, left_clip, right_clip])
    text_clips.append(composite_clip)

# Combine all text clips into a single video
final_video = CompositeVideoClip(text_clips)

# Add the audio to the video
final_video = final_video.set_audio(AudioFileClip(audio_file))

# Save the final video
output_file = "/content/drive/My Drive/output_video.mp4"  # Update with your desired output path
final_video.write_videofile(output_file, fps=1, codec="libx264")

print(f"Video saved to {output_file}")

import moviepy.config as mpy_config
mpy_config.IMAGEMAGICK_BINARY = "/usr/bin/convert"

time_clip = TextClip(
    f"Time: {second} s",
    fontsize=30,
    color="yellow",
    font="Arial",  # Use a known font
    bg_color="black",
    size=(640, 480),
).set_position("top").set_duration(1).set_start(second)

from moviepy.editor import TextClip
TextClip.set_image_backend('pillow')

!pip install pillow

from moviepy.editor import TextClip

# Create the text clip for time
time_clip = TextClip(
    f"Time: {second} s",
    fontsize=30,
    color="yellow",
    font="Arial",  # Arial is commonly available, but you can try others like "Liberation Sans"
    bg_color="black",
    size=(640, 480),  # Adjust the size as needed
).set_position("top").set_duration(1).set_start(second)

# You can now proceed to create other clips (left_clip, right_clip, etc.) the same way.

import moviepy.config as mpy_config
mpy_config.IMAGEMAGICK_BINARY = "/usr/bin/convert"

from moviepy.editor import TextClip, CompositeVideoClip
import numpy as np

# Assuming you already have the necessary arrays for kinematic values
# and forces and motions (distance, displacement, speed, etc.)

# Replace these with your actual calculated arrays
distance = np.random.rand(10)  # Replace with your distance values
displacement = np.random.rand(10)  # Replace with your displacement values
speed = np.random.rand(10)  # Replace with your speed values
velocity = np.random.rand(10)  # Replace with your velocity values
acceleration = np.random.rand(10)  # Replace with your acceleration values
momentum = np.random.rand(10)  # Replace with your momentum values
potential_energy = np.random.rand(10)  # Replace with your potential energy values
kinetic_energy = np.random.rand(10)  # Replace with your kinetic energy values
inertia = np.random.rand(10)  # Replace with your inertia values
impulse = np.random.rand(10)  # Replace with your impulse values

# Forces and motions
forces = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring",
          "Applied", "Drag", "Normal", "Buoyant"]
motions = ["Rotational Motion", "Circular Motion", "Oscillatory Motion",
           "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace these with your actual force magnitude and motion types
force_magnitude = np.random.rand(10)  # Replace with actual force magnitudes
force_type = [forces[np.random.randint(0, len(forces))] for _ in range(10)]
motion_type = [motions[np.random.randint(0, len(motions))] for _ in range(10)]

# Create text clips for each second
text_clips = []
for second in range(len(distance)):
    # Time clip at the top center
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=30,
        color="yellow",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("top").set_duration(1).set_start(second)

    # Left column with kinematic elements
    left_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    left_clip = TextClip(
        left_text,
        fontsize=20,
        color="yellow",
        bg_color="black",
        size=(320, 480),
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Right column with force magnitude, force type, and motion type
    right_text = (
        f"Force Magnitude: {force_magnitude[second]:.4f} N\n"
        f"Force Type: {force_type[second]}\n"
        f"Motion Type: {motion_type[second]}"
    )

    right_clip = TextClip(
        right_text,
        fontsize=24,  # Larger size for clarity
        color="yellow",
        bg_color="black",
        size=(320, 480),
    ).set_position(("right", "center")).set_duration(1).set_start(second)

    # Add clips to the list
    text_clips.append(time_clip)
    text_clips.append(left_clip)
    text_clips.append(right_clip)

# Create the final composite video with all text clips
final_clip = CompositeVideoClip(text_clips, size=(640, 480))  # Set size as needed

# Add audio to the video (assuming audio_file is already loaded)
audio_clip = AudioFileClip("path_to_your_audio.wav")
final_clip = final_clip.set_audio(audio_clip)

# Write the final video to a file
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", fps=24)

audio_clip = AudioFileClip("/content/drive/My Drive/sample.wav")

from moviepy.editor import TextClip, CompositeVideoClip
import numpy as np

# Assuming you already have the necessary arrays for kinematic values
# and forces and motions (distance, displacement, speed, etc.)

# Replace these with your actual calculated arrays
distance = np.random.rand(10)  # Replace with your distance values
displacement = np.random.rand(10)  # Replace with your displacement values
speed = np.random.rand(10)  # Replace with your speed values
velocity = np.random.rand(10)  # Replace with your velocity values
acceleration = np.random.rand(10)  # Replace with your acceleration values
momentum = np.random.rand(10)  # Replace with your momentum values
potential_energy = np.random.rand(10)  # Replace with your potential energy values
kinetic_energy = np.random.rand(10)  # Replace with your kinetic energy values
inertia = np.random.rand(10)  # Replace with your inertia values
impulse = np.random.rand(10)  # Replace with your impulse values

# Forces and motions
forces = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring",
          "Applied", "Drag", "Normal", "Buoyant"]
motions = ["Rotational Motion", "Circular Motion", "Oscillatory Motion",
           "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace these with your actual force magnitude and motion types
force_magnitude = np.random.rand(10)  # Replace with actual force magnitudes
force_type = [forces[np.random.randint(0, len(forces))] for _ in range(10)]
motion_type = [motions[np.random.randint(0, len(motions))] for _ in range(10)]

# Create text clips for each second
text_clips = []
for second in range(len(distance)):
    # Time clip at the top center
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=30,
        color="yellow",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("top").set_duration(1).set_start(second)

    # Left column with kinematic elements
    left_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    left_clip = TextClip(
        left_text,
        fontsize=20,
        color="yellow",
        bg_color="black",
        size=(320, 480),
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Right column with force magnitude, force type, and motion type
    right_text = (
        f"Force Magnitude: {force_magnitude[second]:.4f} N\n"
        f"Force Type: {force_type[second]}\n"
        f"Motion Type: {motion_type[second]}"
    )

    right_clip = TextClip(
        right_text,
        fontsize=24,  # Larger size for clarity
        color="yellow",
        bg_color="black",
        size=(320, 480),
    ).set_position(("right", "center")).set_duration(1).set_start(second)

    # Add clips to the list
    text_clips.append(time_clip)
    text_clips.append(left_clip)
    text_clips.append(right_clip)

# Create the final composite video with all text clips
final_clip = CompositeVideoClip(text_clips, size=(640, 480))  # Set size as needed

# Add audio to the video (assuming audio_file is already loaded)
audio_clip = AudioFileClip("sample.wav")
final_clip = final_clip.set_audio(audio_clip)

# Write the final video to a file
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", fps=24)

audio_clip = AudioFileClip("/content/drive/My Drive/sample.wav")

audio_clip = AudioFileClip("/content/drive/My Drive/sample.wav")

drive.mount('/content/drive')

audio_file = "/content/drive/My Drive/sample.wav"

with open("/content/drive/My Drive/sample.wav", "rb") as f:
    print("File is accessible.")

from moviepy.editor import TextClip, CompositeVideoClip
import numpy as np

# Assuming you already have the necessary arrays for kinematic values
# and forces and motions (distance, displacement, speed, etc.)

# Replace these with your actual calculated arrays
distance = np.random.rand(10)  # Replace with your distance values
displacement = np.random.rand(10)  # Replace with your displacement values
speed = np.random.rand(10)  # Replace with your speed values
velocity = np.random.rand(10)  # Replace with your velocity values
acceleration = np.random.rand(10)  # Replace with your acceleration values
momentum = np.random.rand(10)  # Replace with your momentum values
potential_energy = np.random.rand(10)  # Replace with your potential energy values
kinetic_energy = np.random.rand(10)  # Replace with your kinetic energy values
inertia = np.random.rand(10)  # Replace with your inertia values
impulse = np.random.rand(10)  # Replace with your impulse values

# Forces and motions
forces = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring",
          "Applied", "Drag", "Normal", "Buoyant"]
motions = ["Rotational Motion", "Circular Motion", "Oscillatory Motion",
           "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace these with your actual force magnitude and motion types
force_magnitude = np.random.rand(10)  # Replace with actual force magnitudes
force_type = [forces[np.random.randint(0, len(forces))] for _ in range(10)]
motion_type = [motions[np.random.randint(0, len(motions))] for _ in range(10)]

# Create text clips for each second
text_clips = []
for second in range(len(distance)):
    # Time clip at the top center
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=30,
        color="yellow",
        bg_color="black",
        size=(640, 480),  # Adjust size as needed
    ).set_position("top").set_duration(1).set_start(second)

    # Left column with kinematic elements
    left_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    left_clip = TextClip(
        left_text,
        fontsize=20,
        color="yellow",
        bg_color="black",
        size=(320, 480),
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Right column with force magnitude, force type, and motion type
    right_text = (
        f"Force Magnitude: {force_magnitude[second]:.4f} N\n"
        f"Force Type: {force_type[second]}\n"
        f"Motion Type: {motion_type[second]}"
    )

    right_clip = TextClip(
        right_text,
        fontsize=24,  # Larger size for clarity
        color="yellow",
        bg_color="black",
        size=(320, 480),
    ).set_position(("right", "center")).set_duration(1).set_start(second)

    # Add clips to the list
    text_clips.append(time_clip)
    text_clips.append(left_clip)
    text_clips.append(right_clip)

# Create the final composite video with all text clips
final_clip = CompositeVideoClip(text_clips, size=(640, 480))  # Set size as needed

# Add audio to the video (assuming audio_file is already loaded)
audio_clip = AudioFileClip("/content/drive/My Drive/sample.wav")
final_clip = final_clip.set_audio(audio_clip)

# Write the final video to a file
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", fps=24)

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"  # Replace with the correct path

# Load audio file
audio_clip = AudioFileClip(audio_file)

# Duration of the video in seconds
duration = int(audio_clip.duration)

# Sample data for the values (replace these with your actual calculated values)
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions (replace these with your actual values)
forces = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motions = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Assign random forces and motions (replace with your actual logic)
force_magnitude = np.random.rand(duration) * 10  # in N
force_type = [forces[np.random.randint(0, 9)] for _ in range(duration)]
motion_type = [motions[np.random.randint(0, 6)] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time clip (Top Center)
    time_clip = TextClip(
        f"Time: {second} s", fontsize=40, color="yellow", bg_color="black", size=(640, 480)
    ).set_position("top").set_duration(1).set_start(second)

    # Left column (Kinematic values)
    left_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    left_clip = TextClip(
        left_text, fontsize=20, color="yellow", bg_color="black", size=(320, 480)
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Right column (Force and Motion)
    force_clip = TextClip(
        f"Force: {force_magnitude[second]:.2f} N\nType: {force_type[second]}\nMotion: {motion_type[second]}",
        fontsize=30, color="yellow", bg_color="black", size=(320, 480)
    ).set_position(("right", "center")).set_duration(1).set_start(second)

    # Combine the clips for this second
    clips.extend([time_clip, left_clip, force_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(640, 480)).set_audio(audio_clip)

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Load audio file
audio_clip = AudioFileClip(audio_file)

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic
forces = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motions = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Assign random forces and motions (replace this with your real data)
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = [forces[np.random.randint(0, 9)] for _ in range(duration)]
motion_type = [motions[np.random.randint(0, 6)] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,
        color="yellow",
        bg_color="black"
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_type[second]}\n"
        f"Motion: {motion_type[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=60,
        color="red",
        bg_color="black"
    ).set_position(("left", "bottom")).set_duration(1).set_start(second)

# Combine the clips for this second
    clips.extend([time_clip, left_clip, force_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(640, 480)).set_audio(audio_clip)

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Load audio file
audio_clip = AudioFileClip(audio_file)

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic
forces = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motions = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Assign random forces and motions (replace this with your real data)
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = [forces[np.random.randint(0, 9)] for _ in range(duration)]
motion_type = [motions[np.random.randint(0, 6)] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=25,
        color="yellow",
        bg_color="black",
        method="caption"
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_type[second]}\n"
        f"Motion: {motion_type[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("left", "bottom")).set_duration(1).set_start(second)

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(640, 480)).set_audio(audio_clip)

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

# prompt: The mistake of the video is that text is jumbled. There seems to be overlap of the bbackground of the red text and the background of the yellow text. Additionally the values of the red text are random they are not from the findings/ the results of the cells wehere we deduced the type of force and motion.

# ... (Your existing imports and code)

# ... (Your existing code for loading audio and data)


# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=25,
        color="yellow",
        bg_color="black",
        method="caption"  # Use caption method for better text rendering
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (right-aligned, bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_type[second]}\n"
        f"Motion: {motion_type[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,
        color="red",
        bg_color="black",
        method="caption"  # Use caption method for better text rendering
    ).set_position(("right", "center")).set_duration(1).set_start(second) # Positioned on the right


    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip) # Increased size for better visibility

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Load audio file
audio_clip = AudioFileClip(audio_file)

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
# For demonstration, using random assignment here:
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned) without background (to avoid overlap)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=25,
        color="yellow",
        method="caption"
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("left", "bottom")).set_duration(1).set_start(second)

    # Add space between the clips
    force_motion_clip = force_motion_clip.set_position(("left", 250))  # Adjust this value to get the desired spacing

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(640, 480)).set_audio(audio_clip)

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Load audio file
audio_clip = AudioFileClip(audio_file)

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
# For demonstration, using random assignment here:
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned) without background (to avoid overlap)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=25,
        color="yellow",
        method="caption"
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("left", "bottom")).set_duration(1).set_start(second)

    # Add space between the clips
    force_motion_clip = force_motion_clip.set_position(("left", 250))  # Adjust this value to get the desired spacing

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(640, 480)).set_audio(audio_clip)

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

import os

file_path = "/content/drive/My Drive/sample.wav"
print("File exists:", os.path.exists(file_path))

import os

drive_folder = "/content/drive/My Drive"
for root, dirs, files in os.walk(drive_folder):
    for file in files:
        if file.endswith(".wav"):
            print(os.path.join(root, file))

from google.colab import files

uploaded = files.upload()

for filename in uploaded.keys():
    print(f"Uploaded file: {filename}")

from google.colab import drive
drive.mount('/content/drive')

import os

file_path = "/content/drive/My Drive/sample.wav"
print("File exists:", os.path.exists(file_path))

from moviepy.editor import AudioFileClip

# Correct file path to your audio file in Google Drive
audio_file = "/content/drive/My Drive/sample.wav"

# Load the audio file
audio_clip = AudioFileClip(audio_file)

# Confirm it worked
print(f"Audio loaded successfully! Duration: {audio_clip.duration} seconds.")

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Load audio file
audio_clip = AudioFileClip(audio_file)

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
# For demonstration, using random assignment here:
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned) without background (to avoid overlap)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=25,
        color="yellow",
        method="caption"
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("left", "bottom")).set_duration(1).set_start(second)

    # Add space between the clips
    force_motion_clip = force_motion_clip.set_position(("left", 250))  # Adjust this value to get the desired spacing

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(640, 480)).set_audio(audio_clip)

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

!apt-get update
!apt-get install imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

from moviepy.editor import TextClip

# Create a simple text clip to test
text_clip = TextClip("Hello, MoviePy!", fontsize=70, color="yellow")
text_clip = text_clip.set_duration(3)

# Save the output
text_clip.write_videofile("/content/drive/My Drive/test_video.mp4", fps=24)

!apt-get update
!apt-get install imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

!convert -version

Version: ImageMagick 6.X.X

!convert -version

from moviepy.editor import TextClip

# Test a basic text clip (3 seconds long)
text_clip = TextClip("Test", fontsize=70, color="white", bg_color="black")
text_clip = text_clip.set_duration(3)

# Save the video to Google Drive
text_clip.write_videofile("/content/drive/My Drive/test_video.mp4", fps=24)

!apt-get update
!apt-get install -y imagemagick

!cp /usr/bin/convert /usr/local/bin/convert

!convert -version

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Load audio file
audio_clip = AudioFileClip(audio_file)

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
# For demonstration, using random assignment here:
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned) without background (to avoid overlap)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=25,
        color="yellow",
        method="caption"
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("left", "bottom")).set_duration(1).set_start(second)

    # Add space between the clips
    force_motion_clip = force_motion_clip.set_position(("left", 250))  # Adjust this value to get the desired spacing

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(640, 480)).set_audio(audio_clip)

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

# Install necessary packages
!apt-get update
!apt-get install -y imagemagick
!pip install moviepy

# Ensure ImageMagick policy allows text rendering
!sed -i 's/none/read|write/' /etc/ImageMagick-6/policy.xml

from moviepy.editor import *
from moviepy.video.io.AudioFileClip import AudioFileClip

# Load your audio file from Google Drive
audio_file = "/content/drive/My Drive/sample.wav"
audio_clip = AudioFileClip(audio_file)

# Create a blank video with the same duration as the audio
video = ColorClip(size=(1280, 720), color=(0, 0, 0), duration=audio_clip.duration)

# Add text to the video
txt_clip = TextClip("Your Text Here", fontsize=70, color='white', font='Arial', method='caption')
txt_clip = txt_clip.set_position(('left', 'top')).set_duration(audio_clip.duration)

# Combine text and video
final_video = CompositeVideoClip([video, txt_clip])

# Set audio to the video
final_video = final_video.set_audio(audio_clip)

# Save the final output
output_file = "/content/output_video.mp4"
final_video.write_videofile(output_file, fps=24)

print(f"Video saved at {output_file}")

# Install necessary packages if not already installed
!apt-get update
!apt-get install -y imagemagick
!pip install moviepy

# Ensure ImageMagick policy allows text rendering
!sed -i 's/none/read|write/' /etc/ImageMagick-6/policy.xml

from moviepy.editor import *

# Load your audio file from Google Drive
audio_file = "/content/drive/My Drive/sample.wav"
audio_clip = AudioFileClip(audio_file)

# Create a blank video with the same duration as the audio
video = ColorClip(size=(1280, 720), color=(0, 0, 0), duration=audio_clip.duration)

# Add text to the video
txt_clip = TextClip("Your Text Here", fontsize=70, color='white', font='Arial', method='caption')
txt_clip = txt_clip.set_position(('left', 'top')).set_duration(audio_clip.duration)

# Combine text and video
final_video = CompositeVideoClip([video, txt_clip])

# Set audio to the video
final_video = final_video.set_audio(audio_clip)

# Save the final output
output_file = "/content/output_video.mp4"
final_video.write_videofile(output_file, fps=24)

print(f"Video saved at {output_file}")

!sudo apt-get update
!sudo apt-get install -y imagemagick
!sudo sed -i 's/none/read|write/' /etc/ImageMagick-6/policy.xml

import os
os.environ["MAGICK_HOME"] = "/usr"

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Load audio file
audio_clip = AudioFileClip(audio_file)

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
# For demonstration, using random assignment here:
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned) without background (to avoid overlap)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=25,
        color="yellow",
        method="caption"
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("left", "bottom")).set_duration(1).set_start(second)

    # Add space between the clips
    force_motion_clip = force_motion_clip.set_position(("left", 250))  # Adjust this value to get the desired spacing

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(640, 480)).set_audio(audio_clip)

# Output the final video with the time and values evolving
final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)

import moviepy.editor as mp
from moviepy.config import change_settings

# Set the path to the ImageMagick binary (adjust to your system's actual path)
change_settings({"IMAGEMAGICK_BINARY": "/usr/bin/convert"})  # For Ubuntu systems, might vary for other systems

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip
from google.colab import drive
import numpy as np

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned) with semi-transparent background
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=25,
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",
        method="caption"
    ).set_position(("left", "center")).set_duration(1).set_start(second)

    # Force and Motion (bigger and in red)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("left", 0.6), relative=True).set_duration(1).set_start(second)

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()





from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip

from google.colab import drive
import numpy as np
import os

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left column)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=20,  # Smaller font size to fit in the column
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        method="caption"
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right column)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=30,  # Larger font size for emphasis
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip
from google.colab import drive
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,  # Increased font size
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        method="caption"
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right-aligned)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=40,  # Increased font size
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f"spectrogram_{second}.png", bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create a clip
    spectrogram_image = Image.open(f"spectrogram_{second}.png")
    spectrogram_clip = ImageClip(f"spectrogram_{second}.png").set_duration(1).set_start(second)
    spectrogram_clip = spectrogram_clip.set_position(("center", 0.5), relative=True)  # Middle of the screen

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

    # Clean up spectrogram images
    for second in range(duration):
        os.remove(f"spectrogram_{second}.png")

!apt-get update
!apt-get install -y imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

!apt-get update
!apt-get install -y imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

!convert --version

!apt-get update
!apt-get install -y imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

!apt-get update
!apt-get install -y imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

!apt-get update
!apt-get install -y imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

!apt-get update
!apt-get install -y imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

!convert -version

!apt-get install -y imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"  # Adjust path as needed

!which convert

# Install ImageMagick
!apt-get update
!apt-get install imagemagick

# Set ImageMagick binary path
import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip
from google.colab import drive
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,  # Increased font size
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right-aligned)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=40,  # Increased font size
        color="red",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f"spectrogram_{second}.png", bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create a clip
    spectrogram_image = Image.open(f"spectrogram_{second}.png")
    spectrogram_clip = ImageClip(f"spectrogram_{second}.png").set_duration(1).set_start(second)
    spectrogram_clip = spectrogram_clip.set_position(("center", 0.5), relative=True)  # Middle of the screen

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

    # Clean up spectrogram images
    for second in range(duration):
        os.remove(f"spectrogram_{second}.png")

# Install ImageMagick and necessary library
!apt-get update
!apt-get install imagemagick -y
!apt-get install libmagickwand-dev -y

# Set ImageMagick binary path
import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip
from google.colab import drive
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black",
        # Use 'label' method to avoid ImageMagick dependency
        method='label'
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,  # Increased font size
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        # Use 'label' method to avoid ImageMagick dependency
        method='label'
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right-aligned)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=40,  # Increased font size
        color="red",
        bg_color="black",
        # Use 'label' method to avoid ImageMagick dependency
        method='label'
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f"spectrogram_{second}.png", bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create a clip
    spectrogram_image = Image.open(f"spectrogram_{second}.png")
    spectrogram_clip = ImageClip(f"spectrogram_{second}.png").set_duration(1).set_start(second)
    spectrogram_clip = spectrogram_clip.set_position(("center", 0.5), relative=True)  # Middle of the screen

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

    # Clean up spectrogram images
    for second in range(duration):
        os.remove(f"spectrogram_{second}.png")

!apt-get update
!apt-get install imagemagick -y
!apt-get install libmagickwand-dev -y

# Set ImageMagick binary path
import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

# Explicitly set the path to the 'convert' command
os.environ["PATH"] += os.pathsep + "/usr/bin"  # or wherever 'convert' is located

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip, ImageSequenceClip
from IPython.display import HTML
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image
import os
import gc

from google.colab import drive
drive.mount('/content/drive')

# Define audio and output paths
audio_path = "/content/drive/My Drive/sample.wav"
output_path = "/content/drive/My Drive/output_video.mp4"

# Try to load the audio file with error handling
try:
    audio_clip = AudioFileClip(audio_path)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio clip
duration = int(audio_clip.duration)

# If the audio duration is longer than 10 seconds, trim to 10 seconds to prevent potential crashes
if duration > 10:
    audio_clip = audio_clip.subclip(0, 10)
    duration = 10  # Set duration to 10 seconds

# Sample data for visualization (replace with your calculated values)
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Predefined data for force type and motion type
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]
force_magnitude = np.random.rand(duration) * 10  # in Newtons

# Create text clips for data visualization
clips = []

for second in range(duration):
    # Time text clip
    time_clip = TextClip(f"Time: {second} s", fontsize=50, color="yellow", bg_color="black", method='label') \
        .set_position(("center", "top")) \
        .set_duration(1) \
        .set_start(second)

    # Kinematics values text clip
    kinematics_text = (f"Distance: {distance[second]:.4f}\n"
                       f"Displacement: {displacement[second]:.4f}\n"
                       f"Speed: {speed[second]:.4f}\n"
                       f"Velocity: {velocity[second]:.4f}\n"
                       f"Acceleration: {acceleration[second]:.4f}\n"
                       f"Momentum: {momentum[second]:.4f}\n"
                       f"Potential Energy: {potential_energy[second]:.4f}\n"
                       f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
                       f"Inertia: {inertia[second]:.4f}\n"
                       f"Impulse: {impulse[second]:.4f}")
    kinematics_clip = TextClip(kinematics_text, fontsize=30, color="yellow", bg_color="rgba(0, 0, 0, 0.5)",
                               method='label') \
        .set_position(("left", 0.3), relative=True) \
        .set_duration(1) \
        .set_start(second)

    # Force and Motion text clip
    force_motion_text = (f"Force: {force_magnitude[second]:.2f} N\n"
                         f"Type: {force_values[second]}\n"
                         f"Motion: {motion_values[second]}")
    force_motion_clip = TextClip(force_motion_text, fontsize=40, color="red", bg_color="black", method='label') \
        .set_position(("right", 0.3), relative=True) \
        .set_duration(1) \
        .set_start(second)

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    spectrogram_filename = f"spectrogram_{second}.png"
    plt.savefig(spectrogram_filename, bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create clip
    spectrogram_clip = ImageClip(spectrogram_filename).set_duration(1).set_start(second) \
        .set_position(("center", 0.5), relative=True)

    # Extend the clips list with created clips
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

    # Clean up spectrogram images after use
    os.remove(spectrogram_filename)
    gc.collect()

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Write the video to the output path
try:
    final_clip.write_videofile(output_path, codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()
    gc.collect()

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip
from google.colab import drive
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,  # Increased font size
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right-aligned)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=40,  # Increased font size
        color="red",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f"spectrogram_{second}.png", bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create a clip
    spectrogram_image = Image.open(f"spectrogram_{second}.png")
    spectrogram_clip = ImageClip(f"spectrogram_{second}.png").set_duration(1).set_start(second)
    spectrogram_clip = spectrogram_clip.set_position(("center", 0.5), relative=True)  # Middle of the screen

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

    # Clean up spectrogram images
    for second in range(duration):
        os.remove(f"spectrogram_{second}.png")

!which convert

from google.colab import drive
drive.mount('/content/drive', force_remount=True)

import moviepy.editor as mp
import os

# Set the ImageMagick binary path explicitly (replace with actual path from "which convert")
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"  # Update this if needed

# Try generating the text clip again
txt_clip = mp.TextClip("Test Text", fontsize=50, color='white')
txt_clip.preview()

!pip uninstall moviepy
!pip install moviepy
!sudo apt-get install imagemagick

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip
from google.colab import drive
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,  # Increased font size
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right-aligned)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=40,  # Increased font size
        color="red",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f"spectrogram_{second}.png", bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create a clip
    spectrogram_image = Image.open(f"spectrogram_{second}.png")
    spectrogram_clip = ImageClip(f"spectrogram_{second}.png").set_duration(1).set_start(second)
    spectrogram_clip = spectrogram_clip.set_position(("center", 0.5), relative=True)  # Middle of the screen

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

    # Clean up spectrogram images
    for second in range(duration):
        os.remove(f"spectrogram_{second}.png")

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip
from google.colab import drive
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black"
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,  # Increased font size
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        method="caption"
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right-aligned)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=40,  # Increased font size
        color="red",
        bg_color="black",
        method="caption"
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f"spectrogram_{second}.png", bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create a clip
    spectrogram_image = Image.open(f"spectrogram_{second}.png")
    spectrogram_clip = ImageClip(f"spectrogram_{second}.png").set_duration(1).set_start(second)
    spectrogram_clip = spectrogram_clip.set_position(("center", 0.5), relative=True)  # Middle of the screen

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

    # Clean up spectrogram images
    for second in range(duration):
        os.remove(f"spectrogram_{second}.png")

# Install dependencies
!pip install moviepy numpy matplotlib scipy pillow

# Set ImageMagick binary path
import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip
from google.colab import drive
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,  # Increased font size
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right-aligned)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=40,  # Increased font size
        color="red",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f"spectrogram_{second}.png", bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create a clip
    spectrogram_image = Image.open(f"spectrogram_{second}.png")
    spectrogram_clip = ImageClip(f"spectrogram_{second}.png").set_duration(1).set_start(second)
    spectrogram_clip = spectrogram_clip.set_position(("center", 0.5), relative=True)  # Middle of the screen

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

    # Clean up spectrogram images
    for second in range(duration):
        os.remove(f"spectrogram_{second}.png")

!pip install moviepy numpy matplotlib scipy pillow

import moviepy.editor as mp

!apt-get install imagemagick

import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

import moviepy.editor as mp

!apt update
!apt install imagemagick ffmpeg
!pip install moviepy numpy pydub matplotlib scipy pillow

!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

from moviepy.editor import TextClip, CompositeVideoClip

# Create a simple text clip
text_clip = TextClip("Hello, World!", fontsize=50, color="white", bg_color="black").set_duration(5)

# Create a composite video
final_clip = CompositeVideoClip([text_clip])

# Save the video
final_clip.write_videofile("test_output.mp4", fps=24)

!nvidia-smi  # Check GPU usage
!free -h     # Check RAM usage
!df -h       # Check disk space

pip install moviepy numpy pydub matplotlib scipy pillow



!apt update
!apt install imagemagick ffmpeg
!pip install --upgrade moviepy numpy pydub matplotlib scipy pillow
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

!nvidia-smi  # Check GPU usage
!free -h     # Check RAM usage
!df -h       # Check disk space

# Install dependencies
!apt update
!apt install imagemagick ffmpeg
!pip install moviepy numpy matplotlib scipy pillow

# Configure ImageMagick policy
!sed -i '/<policy domain="path" rights="none" pattern="@\*"/d' /etc/ImageMagick-6/policy.xml

# Set ImageMagick binary path
import os
os.environ["IMAGEMAGICK_BINARY"] = "/usr/bin/convert"

# Import libraries
from moviepy.editor import AudioFileClip, TextClip, CompositeVideoClip, ImageClip
from google.colab import drive
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
from PIL import Image

# Mount Google Drive
drive.mount('/content/drive')

# Path to your audio file
audio_file = "/content/drive/My Drive/sample.wav"

# Check if audio file exists
if not os.path.exists(audio_file):
    print(f"Audio file not found: {audio_file}")
    exit()

try:
    # Load audio file
    audio_clip = AudioFileClip(audio_file)
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

# Get the duration of the audio in seconds
duration = int(audio_clip.duration)

# Sample data for kinematics — replace these with your actual calculated values
distance = np.random.rand(duration)
displacement = np.random.rand(duration)
speed = np.random.rand(duration)
velocity = np.random.rand(duration)
acceleration = np.random.rand(duration)
momentum = np.random.rand(duration)
potential_energy = np.random.rand(duration)
kinetic_energy = np.random.rand(duration)
inertia = np.random.rand(duration)
impulse = np.random.rand(duration)

# Forces and motions — replace with your actual logic or findings
force_magnitude = np.random.rand(duration) * 10  # in Newtons
force_type = ["Tension", "Friction", "Gravity", "Electromagnetic", "Spring", "Applied", "Drag", "Normal", "Buoyant"]
motion_type = ["Rotational Motion", "Circular Motion", "Oscillatory Motion", "Projectile Motion", "Linear Motion", "Random Motion"]

# Replace with actual calculated or pre-determined force and motion types for each second
force_values = [force_type[np.random.randint(0, len(force_type))] for _ in range(duration)]
motion_values = [motion_type[np.random.randint(0, len(motion_type))] for _ in range(duration)]

# Create text clips for each second
clips = []
for second in range(duration):
    # Time evolving (top)
    time_clip = TextClip(
        f"Time: {second} s",
        fontsize=50,
        color="yellow",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("center", "top")).set_duration(1).set_start(second)

    # Kinematics values (left-aligned)
    kinematics_text = (
        f"Distance: {distance[second]:.4f}\n"
        f"Displacement: {displacement[second]:.4f}\n"
        f"Speed: {speed[second]:.4f}\n"
        f"Velocity: {velocity[second]:.4f}\n"
        f"Acceleration: {acceleration[second]:.4f}\n"
        f"Momentum: {momentum[second]:.4f}\n"
        f"Potential Energy: {potential_energy[second]:.4f}\n"
        f"Kinetic Energy: {kinetic_energy[second]:.4f}\n"
        f"Inertia: {inertia[second]:.4f}\n"
        f"Impulse: {impulse[second]:.4f}"
    )

    kinematics_clip = TextClip(
        kinematics_text,
        fontsize=30,  # Increased font size
        color="yellow",
        bg_color="rgba(0, 0, 0, 0.5)",  # Semi-transparent background
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("left", 0.3), relative=True).set_duration(1).set_start(second)  # Left column

    # Force and Motion (right-aligned)
    force_motion_text = (
        f"Force: {force_magnitude[second]:.2f} N\n"
        f"Type: {force_values[second]}\n"
        f"Motion: {motion_values[second]}"
    )

    force_motion_clip = TextClip(
        force_motion_text,
        fontsize=40,  # Increased font size
        color="red",
        bg_color="black",
        method='label'  # Use 'label' method to avoid ImageMagick dependency
    ).set_position(("right", 0.3), relative=True).set_duration(1).set_start(second)  # Right column

    # Generate spectrogram for the current second
    audio_data = audio_clip.to_soundarray(fps=44100)[second * 44100:(second + 1) * 44100, 0]
    f, t, Sxx = spectrogram(audio_data, fs=44100, nperseg=1024)
    plt.figure(figsize=(4, 3))
    plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f"spectrogram_{second}.png", bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close()

    # Load spectrogram image and create a clip
    spectrogram_image = Image.open(f"spectrogram_{second}.png")
    spectrogram_clip = ImageClip(f"spectrogram_{second}.png").set_duration(1).set_start(second)
    spectrogram_clip = spectrogram_clip.set_position(("center", 0.5), relative=True)  # Middle of the screen

    # Combine the clips for this second
    clips.extend([time_clip, kinematics_clip, force_motion_clip, spectrogram_clip])

# Create the composite video
final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)

# Output the final video with the time and values evolving
try:
    final_clip.write_videofile("/content/drive/My Drive/output_video.mp4", codec="libx264", fps=24)
except Exception as e:
    print(f"Error writing video file: {e}")
finally:
    final_clip.close()
    audio_clip.close()

    # Clean up spectrogram images
    for second in range(duration):
        os.remove(f"spectrogram_{second}.png")

from moviepy.editor import AudioFileClip

# Load the audio file
audio_file = "/content/drive/My Drive/sample.wav"
try:
    audio_clip = AudioFileClip(audio_file)
    print(f"Audio clip duration: {audio_clip.duration} seconds")
    print(f"Audio clip fps: {audio_clip.fps}")
except Exception as e:
    print(f"Error loading audio file: {e}")
    exit()

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import spectrogram

# Extract audio data for the first second
audio_data = audio_clip.to_soundarray(fps=44100)
segment = audio_data[:44100, 0]  # First second of audio

# Generate the spectrogram
f, t, Sxx = spectrogram(segment, fs=44100, nperseg=1024)
plt.figure(figsize=(4, 3))
plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')
plt.axis('off')
plt.tight_layout()
plt.savefig("spectrogram.png", bbox_inches='tight', pad_inches=0, transparent=True)
plt.close()

# Load spectrogram image and create a clip
from moviepy.editor import ImageClip
spectrogram_clip = ImageClip("spectrogram.png").set_duration(1)

# Combine text and spectrogram clips
final_clip = CompositeVideoClip([text_clip, spectrogram_clip], size=(1280, 720)).set_audio(audio_clip)

# Save the video
output_file = "test_output.mp4"
final_clip.write_videofile(output_file, codec="libx264", fps=24)
print(f"Video saved to {output_file}")

audio_data = audio_clip.to_soundarray(fps=44100)
print(f"Audio data shape: {audio_data.shape}")

print(f"Time clip: {time_clip}")
print(f"Kinematics clip: {kinematics_clip}")
print(f"Force motion clip: {force_motion_clip}")
print(f"Spectrogram clip: {spectrogram_clip}")

if os.path.exists(f"spectrogram_{second}.png"):
    print(f"Spectrogram image for second {second} saved successfully.")
else:
    print(f"Failed to save spectrogram image for second {second}.")

from moviepy.editor import TextClip

# Example: creating a simple text clip to check
test_clip = TextClip("Test", fontsize=50, color='white', size=(1280, 720)).set_duration(5)
clips.append(test_clip)

from moviepy.editor import TextClip

# Initialize an empty list for clips
clips = []

# Example: creating a simple text clip
test_clip = TextClip("Test", fontsize=50, color='white', size=(1280, 720)).set_duration(5)
clips.append(test_clip)

# Check the clips list
print("Number of clips:", len(clips))
print("Clips content:", clips)

for clip in clips:
    print("Clip duration:", clip.duration)

if any(clip.duration is None for clip in clips):
    print("Warning: Some clips have no duration set.")

if clips:
    final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)
else:
    print("No valid clips to combine.")

# Example: load an audio file (replace 'your_audio_file.wav' with your file path)
audio_clip = AudioFileClip('your_audio_file.wav')

# Combine the video and audio clips
if clips:
    final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)
    final_clip.write_videofile("output_video.mp4", fps=24)
else:
    print("No valid clips to combine.")

from moviepy.editor import CompositeVideoClip, TextClip, AudioFileClip

# Example: load an audio file (replace 'sample.wav' with your file path)
audio_clip = AudioFileClip('sample.wav')

# Combine the video and audio clips
if clips:
    final_clip = CompositeVideoClip(clips, size=(1280, 720)).set_audio(audio_clip)
    final_clip.write_videofile("output_video.mp4", fps=24)
else:
    print("No valid clips to combine.")

from google.colab import drive
drive.mount('/content/drive')

audio_clip = AudioFileClip('/content/drive/My Drive/sample.wav')

audio_clip = AudioFileClip('/content/drive/My Drive/your_folder/sample.wav')

!find /content/drive/My\ Drive/ -name "sample.wav"

audio_clip = AudioFileClip('your_correct_path_here/sample.wav')

!find /content/drive/My\ Drive/ -name "sample.wav"

audio_clip = AudioFileClip('/content/drive/My Drive/your_actual_folder/sample.wav')

from moviepy.editor import AudioFileClip

# Correct path to your audio file
audio_clip = AudioFileClip('/content/drive/My Drive/sample.wav')

# Confirm it's loaded
print(f"Audio duration: {audio_clip.duration} seconds")

AudioFileClip('/content/drive/My Drive/your_folder/sample.wav')

from moviepy.editor import AudioFileClip

# Correct path to your file
audio_clip = AudioFileClip('/content/drive/My Drive/sample.wav')  # If it's directly in 'My Drive'
# Or, if it's inside a folder:
# audio_clip = AudioFileClip('/content/drive/My Drive/your_folder/sample.wav')

# Confirm audio loaded correctly
print(f"Audio duration: {audio_clip.duration} seconds")

!find /content/drive/My\ Drive/ -name "sample.wav"